[Chartjs]-Using Charts.js with react

2πŸ‘

βœ…

There is a React wrapper around ChartJS available from ReactJS organisation on GitHub. It does support bar charts. Maybe try this (if not as a solution, then as a source of inspiration)

29πŸ‘

I have been using react-charjs and react-chart-js2 and it seems they have their own limitation if you want more control you can directly use Chartjs in you component.

import React from "react";
var Chart = require("chart.js");

class Layout extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    const node = this.node;

    var myChart = new Chart(node, {
      type: "bar",
      data: {
        labels: ["Red", "Blue", "Yellow"],
        datasets: [
          {
            label: "# of Likes",
            data: [12, 19, 3],
            backgroundColor: [
              "rgba(255, 99, 132, 0.2)",
              "rgba(54, 162, 235, 0.2)",
              "rgba(255, 206, 86, 0.2)"
            ]
          }
        ]
      }
    });
  }

  render() {
    return (
      <div>
        <canvas
          style={{ width: 800, height: 300 }}
          ref={node => (this.node = node)}
        />
      </div>
    );
  }
}

export default Layout;

1πŸ‘

I have been using react-chartjs-2 for quite some time with all my react projects. It is also a wrapper around chartjs library so you can access all the functionalities as mentioned in the chartjs documentation.

You can go through the npm library of react-chartjs-2 for more info https://www.npmjs.com/package/react-chartjs-2

0πŸ‘

You might want to take a look at a library named Recharts. I think it is a wrapper that uses Chartjs internally and has built in components for different types of charts which you can leverage to built your own charts by supplying data. It might not be fully customizable but surely will help to have a cleaner implementation as long as your React code in concerned to have basic chart components

0πŸ‘

Here is a wrapper component built with newer React hooks

export default function Graph({ className, maxHeight, type, data, options }) {
  const graphRef = useRef(null);

  useEffect(() => {
    if (graphRef.current) {
      new Chart(graphRef.current.getContext("2d"), {
        type,
        data,
        options,
      });
    }
  }, [graphRef.current, type, data, options]);

  return (
    <div className={className || ""}>
      <canvas ref={graphRef} style={maxHeight ? { maxHeight } : null} />
    </div>
  );
}

And use like below to pass data to chart.js

<Graph
  className="col-md-4"
  maxHeight="200px"
  type="bar"
  data={{...}}
  options={{...}}
/>

Leave a comment