How To Implement the Doughnut Graph Using React Chart.Js
As I mentioned in following article there are lots of plugins to implement doughnut charts and all are not supporting all things what developers need. This POC (proof of Content) is done to accommodate following doughnut chart with a tooltip.
As a first step we need to install node.js and create a new react project. For better coding install Visual studio code (You can choose any IDE which supports react.js). Refer follwoing link for installation and project creation.
Once installation and project creation are done install chart.js plugin using terminal.
npm install --save react-chartjs-2 chart.js
Create ‘CreateDoughnutData.js’ under src folder and add following code to there.
import React from 'react';
import {Chart, ArcElement, Tooltip, Legend, Title} from 'chart.js';
import {Doughnut} from 'react-chartjs-2';
Chart.register(ArcElement, Tooltip, Legend, Title);
Chart.defaults.plugins.tooltip.backgroundColor = 'rgb(0, 0, 156)';
Chart.defaults.plugins.legend.position = 'right';
Chart.defaults.plugins.legend.title.display = true;
Chart.defaults.plugins.legend.title.text = '60 of 100 Done';
Chart.defaults.plugins.legend.title.font = 'Helvetica Neue';
const data = {
labels: [
'processed',
'pending'
],
datasets: [{
data: [60,40],
backgroundColor: [
'rgb(0, 197, 0)',
'rgb(204, 223, 243)'
],
borderWidth: 2,
radius: '40%'
}]
};
function CreateDoughnutData() {
return (
<div>
<h2>Requests Summary Widget</h2>
<Doughnut data={data} />
</div>
);
}
export default CreateDoughnutData;
Explanation of <Doughnut data={data} />
In chart.js there is a component for ‘Doughnut Charts’. Once you create data in ‘CreateDoughnutData.js’ it will pass to chart.js ‘Doughnut’ component.
Add following code to App.js
import React from 'react';
import './App.css';
import CreateDoughnutData from './CreateDoughnutData';
function App() {
return (
<div className="App">
<CreateDoughnutData/>
</div>
);
}
export default App;
build the app
npm run build
Start the app
npm start
Open the browser and go to http://localhost:3000 (This is according to the local server you used. Here I’m using 3000 port). You will see the chart.
Folder Structure