12

I am using React and want to tie it in with Chart.js.

The graph below works, but I am not sure how to make a Graph component in React.

My Chart.js code looks like the following:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    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)'
        ] 
     }]
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

I then tried to incorporate this into React. Unfortunately, this didn't work.

My code attempt can be seen here.This is kind of working, but not really, and I have no idea what approach to take.

var Graph = React.createClass({

    render: function() {
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
           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)'
               ] 
            }]
          }
       });
    }
})

5 Answers5

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;
Reyansh Mishra
  • 1,879
  • 1
  • 14
  • 26
  • 1
    you lost 'this.node = React.createRef();' in the constructor – Ging3r Jun 03 '19 at 21:10
  • @Ging3r it is not required to declare that in the constructor. He is assigning `this.node` in-line inside of the `ref` function which defines it for the entire context of the class component. His code will still work as is. – Phil Aug 25 '19 at 19:39
  • hi, how can i do this with function component? – Roby Cigar Feb 26 '21 at 08:00
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)

Mchl
  • 61,444
  • 9
  • 118
  • 120
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

Dinesh Nadimpalli
  • 1,441
  • 1
  • 13
  • 23
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

Yogesh D
  • 1,663
  • 2
  • 23
  • 38
  • [It looks like Recharts wraps D3](https://github.com/recharts/recharts/blob/33350ea/package.json#L56-L61), which is much heavier than Chart.js. – Ian Dunn Nov 26 '19 at 21:03
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={{...}}
/>
Elnoor
  • 3,401
  • 4
  • 24
  • 39