Search code examples
reactjsreact-chartjs

How to create a Pie chart in react?


I have tried to create pie chart like this:


import React from 'react';
import {Pie} from 'react-chartjs-2';

const state = {
  labels: ['January', 'February', 'March','April',
            'May', 'June', 'July', 'August',
            'September', 'October', 'November', 'December'],
  dataset: [
    {
      label: 'Rainfall',
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 1,
      data: [65, 59, 80, 81, 56, 34, 97, 25,69,75,62,45]
    }
  ]
}

export default class PieChartComponent extends React.Component {
  render() {
    return (
      <div className="container">
        <Pie
          data={state}
          options={{
            title:{
              display:true,
              text:'Average Rainfall per month',
              fontSize:16
            },
            legend:{
              display:true,
              position:'right'
            }
          }}
        />
      </div>
    );
  }
}

Solution

  • There is a small typo where you defined the state:

    const state = {
      labels: ['January', 'February', 'March','April',
                'May', 'June', 'July', 'August',
                'September', 'October', 'November', 'December'],
      datasets: [
        {
          label: 'Rainfall',
          backgroundColor: 'rgba(75,192,192,1)',
          borderColor: 'rgba(0,0,0,1)',
          borderWidth: 1,
          data: [65, 59, 80, 81, 56, 34, 97, 25,69,75,62,45]
        }
      ]
    }
    

    Change dataset to datasets. It will work.