6

I'm trying to show bar chart in the reactjs. i also downloaded dependecies of bar chart chart.js and react-chartjs-2

   "chart.js": "^3.6.0",
    "react": "^17.0.2",
    "react-chartjs-2": "^4.0.0",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",

but bar chart not showing content and I'm still getting the error

Reactjs

import React from "react";
import { Bar } from "react-chartjs-2";
const BarComponent = () => {
  return (
    <>
      <Bar
        width={600}
        height={400}
        data={{
          labels: ["January", "February", "March", "April", "May", "June"],
          datasets: [
            {
              label: "months",
              data: [12, 19, 3, 5, 2, 3],
              backgroundColor: "red",
            },
          ],
        }}
      />
    </>
  );
};
export default BarComponent;

What could I be missing here?

Pradip Chinta
  • 61
  • 1
  • 2

1 Answers1

11

You've missed the register part, try adding this.

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

and then register it outside your component

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

you can refer to the example in there documentation here

Omer Khan
  • 437
  • 2
  • 8