Search code examples
reactjschart.jsreact-chartjs-2

react-chartjs-2 with chartJs 3: Error "arc" is not a registered element


I am working on a React app where i want to display charts. I tried to use react-chartjs-2 but i can't find a way to make it work. when i try to use Pie component, I get the error: Error: "arc" is not a registered element.

I did a very simple react app:

  • npx create-react-app my-app
  • npm install --save react-chartjs-2 chart.js

Here is my package.json:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "chart.js": "^3.6.0",
    "cra-template": "1.1.2",
    "react": "^17.0.2",
    "react-chartjs-2": "^4.0.0",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

And here is my App.js file:

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

const BarChart = () => {
  return (
    <Pie
      data={{
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [
          {
            label: '# of votes',
            data: [12, 19, 3, 5, 2, 3],
          },
        ],
      }}
      height={400}
      width={600}
    />
  )
}

const App = () => {
  return (
    <div>
      <BarChart />
    </div>
  )
}

export default App

I also tried to follow this toturial: https://www.youtube.com/watch?v=c_9c5zkfQ3Y&ab_channel=WornOffKeys

He uses an older version of charJs and react-chartjs-2. And when i replace my versions of react-chartjs-2 and chartjs it works on my app.

"chart.js": "^2.9.4",
"react-chartjs-2": "^2.10.0",

Do anyone one know how to solve the error i have (without having to keep old versions of chartJs and react-chartjs-2) ?


Solution

  • Chart.js is treeshakable since chart.js V3 so you will need to import and register all elements you are using.

    import {Chart, ArcElement} from 'chart.js'
    Chart.register(ArcElement);
    

    For all available imports and ways of registering the components you can read the normal chart.js documentation