2

I am trying to add line chart from chart js in react component. I have tried the following code but its showing white screen and no errors. I couldn't figure out what i did wrong. I went through chart.js documentation and got confused. Please give me suggestion how can i display the chart. I'm using react-chartjs-2 version 4.0.0 and chart.js version 3.7.0.

import React from "react";
import {Line} from 'react-chartjs-2';

const data = {
    labels: ['January', 'February', 'March', 'April', 'May'],
    datasets: [
      {
        label: 'Rainfall',
        fill: false,
        lineTension: 0.5,
        backgroundColor: 'rgba(75,192,192,1)',
        borderColor: 'rgba(0,0,0,1)',
        borderWidth: 2,
        data: [65, 59, 80, 81, 56]
      }
    ]
  }

  const config = {
    type: 'line',
    data: data,
    options: {
      responsive: true,
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'Chart.js Line Chart'
        }
      }
    },
  };

const SavingsChart = () => {
    return (
          <Line
            data={data}
            options={config}
          />
      );
};

export default SavingsChart;
uminder
  • 23,831
  • 5
  • 37
  • 72
charlie2
  • 150
  • 2
  • 10
  • I encountered a similar issue, forgot to register the Chart,js elements https://thecodeframework.com/how-to-use-chart-js-with-react-typescript/ – Gagan Jul 02 '22 at 19:51

3 Answers3

3

You should register the chart from chart.js

See an example here

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);
Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45
0

You can try to add this line in the beginning of your file, it seems to fix this issue: import Chart from "chart.js/auto";

TheTisiboth
  • 1,431
  • 1
  • 6
  • 13
0

You could create the chart in the render() method.

render() {
  return (
    <Line 
      data={this.state.data}
      options={this.state.options}
    />
  );
}

Please take a look at the following StackBlitz and see how it works with your amended code.

uminder
  • 23,831
  • 5
  • 37
  • 72