user6002037
user6002037

Reputation:

Using Charts.js with react

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)'
               ] 
            }]
          }
       });
    }
})

Upvotes: 13

Views: 20893

Answers (5)

Elnoor
Elnoor

Reputation: 3752

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={{...}}
/>

Upvotes: 1

Dinesh Nadimpalli
Dinesh Nadimpalli

Reputation: 1491

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

Upvotes: 1

Yogesh D
Yogesh D

Reputation: 1681

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

Upvotes: 0

Reyansh Mishra
Reyansh Mishra

Reputation: 1915

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;

Upvotes: 31

Mchl
Mchl

Reputation: 62387

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)

Upvotes: 2

Related Questions