14

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 Answers 5

31

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;
Sign up to request clarification or add additional context in comments.

3 Comments

you lost 'this.node = React.createRef();' in the constructor
@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.
hi, how can i do this with function component?
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)

2 Comments

Note: the react-chartjs library mentioned in this answer has been archived
Not the expected answer
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

Comments

1

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

Comments

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

1 Comment

It looks like Recharts wraps D3, which is much heavier than Chart.js.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.