Trusted answers to developer questions

How to use chart.js to create charts in React

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

There are several npm packages that allow charts to be created in React; chart.js is one of the packages which makes the creation of charts and graphs ​very easy.

The React wrapper for chart.js is react-chartjs-2; it makes things simpler in React, however, it doesn’t support all the customization features that come with Chart.js.

Both these packages need to be installed using npm before they can be used.

Types of charts:

  1. Bar charts
  2. Line graph
  3. Pie charts

Examples

Let’s look at a some types of charts that can be created using this handy library:

1. Bar chart

import React from 'react';

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Explanation

  • The state variable contains all the data and styling properties of the bar graph. The labels keyword assigns names to each bar, and the dataset sub-set contains information such as bar color, border width, ​and height of the bar.
  • The Bar component is rendered using <Bar /> inside the React App component. The defined state is assigned to the bar component on line 22. The options property allows further miscellaneous styling, such as the position of the heading and the chart legend.

2. Line graph

The syntax is similar to the one used for a bar chart. A new property, lineTension, is used here; it controls the curvature of the line joining the points.

import React from 'react';

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

2. Pie charts

In addition to the conventional pie chart, chart.js also has a Doughnut graph which stylizes the pie chart differently. Both of these charts are represented below:

import React from 'react';

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Additional examples

More types of supported graphs and charts, along with the details about their properties,​ can be found on chart.js's github.

RELATED TAGS

charts
react
chart.js
graph
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?