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;
0

3 Answers 3

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

Comments

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";

Comments

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.