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:
Let’s look at a some types of charts that can be created using this handy library:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
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.<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.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') );
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') );
More types of supported graphs and charts, along with the details about their properties, can be found on chart.js
's github.