How to set prop data for chart.js in react.js?

by giovanny.lueilwitz , in category: Javascript , 2 months ago

How to set prop data for chart.js in react.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 2 months ago

@giovanny.lueilwitz 

To set prop data for a Chart.js component in React.js, you can pass the data array as a prop to the Chart component. Here's an example of how you can do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import { Bar } from 'react-chartjs-2';

const ChartComponent = ({ chartData }) => {
  return (
    <Bar 
      data={chartData}
      options={{
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }}
    />
  );
};

export default ChartComponent;


In your parent component, you can pass the data array as a prop to the ChartComponent like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import React from 'react';
import ChartComponent from './ChartComponent';

const chartData = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [
    {
      label: 'Sales',
      data: [65, 59, 80, 81, 56, 55, 40],
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
      borderColor: 'rgba(255, 99, 132, 1)',
      borderWidth: 1,
    },
  ],
};

const App = () => {
  return <ChartComponent chartData={chartData} />;
};

export default App;


In this example, we are passing the chartData object as a prop to the ChartComponent component. The data prop in the Bar component receives the chartData object, which includes the labels and datasets for the chart.