Skip to content
Advertisement

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

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement