31

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) ?

Vince M
  • 890
  • 1
  • 9
  • 21

9 Answers9

60

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

LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • Hi. I had the same problem copied your code and now works just fine but without `Chart.register(ArcElement);` Thanks. What does it mean treeshakable ? I believe this is a bug why do we have to be hacking around to solve a simple issue like this. – TOMAS Nov 25 '21 at 22:49
  • 2
    in case someone else wondering where to put this code. just copy & paste at the end of your imports. no matter what variation of `react-chartjs-2` are you using – Mani May 05 '22 at 08:16
  • Also fixes the same problem with chartjs and Vue – danbars Apr 28 '23 at 12:36
15

I ran into the same issue earlier, found the solution on react-chartjs-2 documentation page: https://react-chartjs-2.netlify.app/docs/migration-to-v4#tree-shaking

import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';

<Chart type='line' data={chartData} />

All you have to do is to add this line import 'chart.js/auto';

Dharman
  • 30,962
  • 25
  • 85
  • 135
september 21st
  • 187
  • 1
  • 7
  • 2
    Downside of this approach is that you import everything from chart.js, also the things you are not using so your bundle size will increase – LeeLenalee Dec 30 '21 at 21:57
  • This worked for me. Thanks! But I don't know why. Could it also be solved by importing a specific method from Charts instead of just all of them? I'm assuming that's what `import 'chart.js/auto';` does, importing all of them. – NubSteel Mar 22 '23 at 13:18
3

In my case this worked:

import React from "react";
import { ArcElement } from "chart.js";
import Chart from "chart.js/auto";
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 09 '22 at 14:15
2
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';

ChartJS.register(ArcElement, Tooltip, Legend);
Hoang Long
  • 446
  • 4
  • 5
2

You can simply use this. worked for me,

    {import { Doughnut, Pie } from "react-chartjs-2";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";

ChartJS.register(ArcElement, Tooltip, Legend);}

and for changing the height and width values

{<Pie
   data={data}
   width={300}
   height={300}
   options={{ maintainAspectRatio: false }}
/>}
Mohammed ziou
  • 91
  • 1
  • 6
2

In react, I also faced the same issue with doughnut charts.npm i react-chartjs-2 chart.js Documentation says to install this in frontend frameworks; I was using React.

import {Chart,ArcElement} from 'chart.js';
import {Doughnut} from 'react-chartjs-2'


    Chart.register(ArcElement)
    
    const data = {
    };
    
    function Graph() {
      return (
       <div></div>
      )
    }
    
    export default Graph

after importing ArcElement from chart.js and Chart.register(ArcElement) fixed my issue

Krishnadev. V
  • 345
  • 2
  • 8
  • 23
1

In my case this is what worked for me : I imported chart & registrables & ArcElement in one import

import { Chart, registerables, ArcElement } from "chart.js";
Chart.register(...registerables);
Chart.register(ArcElement);
selmanioui
  • 138
  • 1
  • 8
  • 1
    You are registering the arcElement twice, everyhting that is registerable is already in the `registerables` variable – LeeLenalee Jan 04 '22 at 14:15
1

from the react-chartjs-2 docs : As you can see in migration to v4 guide:

v4 of this library, just like Chart.js v3, is tree-shakable. It means that you need to import and register the controllers, elements, scales, and plugins you want to use.

For a list of all the available items to import, see Chart.js docs.

So you should register missed components. For example, if you have Uncaught Error: "arc" is not a registered element. error, you should register ArcElement:

import { ArcElement } from "chart.js";

ChartJS.register(ArcElement);
0
[my app displayed on browser][1]


  [1]: https://i.stack.imgur.com/i4Owk.jpg
My app compiled without errors but my chart(Doghnut) is not been displayed on the browser.

here is my details component where i imported and used it 

import React from 'react';
import { Card, CardHeader, CardContent, Typography } from '@material-ui/core';
import {Chart, ArcElement} from 'chart.js';
import { Doughnut } from 'react-chartjs-2';

import useStyles from './styles';
import useTransactions from '../../useTransactions';
Chart.register(ArcElement)
const Details = ({ title, subheader }) => {
  const { total, chartData } = useTransactions(title);
  const classes = useStyles();

  return (
    <Card className={title === 'Income' ? classes.income : classes.expense}>
      <CardHeader title={title} subheader={subheader} />
      <CardContent>
        <Typography variant="h5">${total}</Typography>
        <Doughnut data={chartData} />
      </CardContent>
    </Card>
  );
};

export default Details;




here also is my package.json file
{
  "name": "tracker",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.12.4",
    "@material-ui/icons": "^4.11.3",
    "@material-ui/lab": "^4.0.0-alpha.61",
    "@speechly/react-client": "^2.2.3",
    "@speechly/react-ui": "^2.7.5",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "chart.js": "^4.3.0",
    "react": "^16.12.0",
    "react-chartjs-2": "^5.2.0",
    "react-dom": "^16.12.0",
    "react-scripts": "5.0.1",
    "uuid": "^9.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}


my app.js file where i imported my details component above
import React, { useEffect, useRef } from 'react';
import { Grid } from '@material-ui/core';

import { SpeechState, useSpeechContext } from "@speechly/react-client";
import { PushToTalkButton, PushToTalkButtonContainer } from '@speechly/react-ui';

import  Details from './components/Details/Details';
import  Main from './components/Main/Main';

import useStyles from './styles';

const App = () => {
  const classes = useStyles();
  const { speechState } = useSpeechContext();
  const main = useRef(null);

  const executeScroll = () => main.current.scrollIntoView() ;   

  useEffect(() => {
    if (speechState === SpeechState.Recording) {
      executeScroll();
    }
  }, [speechState]);

  return (
    <div>
      <Grid className={classes.grid} container spacing={0} alignItems="center" justifyContent ="center" style={{ height: '100vh'}}>
        <Grid item xs={12} sm={4} className={classes.mobile}>
          <Details title="Income" />
        </Grid>
        <Grid ref={main} item xs={12} sm={3} className={classes.main}>
          <Main />
        </Grid>
        <Grid item xs={12} sm={4} className={classes.desktop}>
          <Details title="Income" />
        </Grid>
        <Grid item xs={12} sm={4} className={classes.last}>
          <Details title="Expense" />
        </Grid>
        <PushToTalkButtonContainer>
          <PushToTalkButton />   
        </PushToTalkButtonContainer>
      </Grid>
    </div>
  );
};

export default App;




 I do not know where the problem is coming from

here is my index.js file
import React from 'react';
import  ReactDOM  from 'react-dom';
import {SpeechProvider} from '@speechly/react-client';

import { Provider } from "./context/context";

import App from './App';
import './index.css';

    ReactDOM.render(
        <SpeechProvider appid='60b621bc-87ac-41e5-b500-0b7a66f96317' language='en-US'>
            <Provider>
              <App/>
            </Provider>
        </SpeechProvider>,
        
 

document.getElementById ('root') );