How to Use React and Chart.js

June 9, 2021, 6:13 p.m.
JavaScript React · 4 min read
How to Use React and Chart.js
Last Modified: June 28, 2021, 12:51 p.m.

Use Chart.js to add charts and graphs to any React project. 

 

React Chart.js Packages

There are packages like react-chartjs-2 that integrate Chart.js with React. 

Feel free to use these packages however, for this tutorial, we'll integrate Chart.js and React ourselves to maintain a higher level of Chart.js customization.

 

What is React?

React is a JavaScript library developed and maintained by Facebook. Open-source, React is used to build reusable UI components and user interfaces. 

 

Create a React app

Windows Command Prompt

C:\Users\Owner\desktop\react> npx create-react-app react-chartjs

First, create a React app. Use the official create-react-app project to get started and name the app react-chartjs.

If you are new to React, refer to the beginner's guide before continuing. There are a few necessary packages installations required to use React.  

 

Start the React app

Windows Command Prompt

C:\Users\Owner\desktop\react> cd react-chartjs
C:\Users\Owner\desktop\react\react-chartjs> npm start

Once the installation process is completed, cd or enter into the newly created project directory react-chartjs

Then run the command npm start to run the predefined command specified in the package's scripts object. 

If you're curious, the script is located in react-chartjs > package.json and runs the command react-scripts start when called. 

...
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

...

 

Terminate batch job for React app

Windows Command Prompt

Terminate batch job (Y/N)? y

C:\Users\Owner\Desktop\react\react-chartjs>

Ctrl + C and type y to terminate the job and have the command prompt reappear. 

 

 

What is Chart.js?

Chart.js is a package that uses canvas elements to render animated, responsive charts.  There are nine different types of charts available for Chart.js. Each can be customized.

 

Install Chart.js

Windows Command Prompt

C:\Users\Owner\Desktop\react\react-chartjs>npm install chart.js

Install Chart.js. 

 

How to use Chart.js and React

With the installation complete, it's time to configure the project. 

 

Create a LineChart Class Component

react-chartjs > src > (New Folder) components > (New File) LineChart.js

import React, { Component } from 'react';
import Chart from 'chart.js/auto';

export default class LineChart extends Component {

	
}

Open the project directory in a text editor. Then create a new folder called components.

Next, create a new file called LineChart.js.  

Import React and Component then import Chart form 'chart.js/auto'.

This is a one-line solution to importing and registering all of the controllers, elements, scales, and plugins from Chart.js. 

Now create a new component called LineChart.

Let's export and define the component in the same line. 

 

Add a Chart to the LineChart Class Component

react-chartjs > src > components > LineChart.js

import React, { Component } from 'react';
import Chart from 'chart.js/auto';

export default class LineChart extends Component {

	chartRef = React.createRef();

	componentDidMount() {
		const ctx = this.chartRef.current.getContext("2d");

		new Chart(ctx, {
			
			},
		});
	}
	render() {
		return (
			<div>
				<canvas
				id="myChart"
				ref={this.chartRef}
				/>
			</div>
			)
	}
}

Continuing on, create a new variable called chartRef and set it equal to React.createRef()

React.createRef() is used to set an element's current state as the instance received from ComponentDidMount() by allowing access to an element created in the render method, in this case, the canvas element.

In that case, add ComponentDidMount() and create a new chart within the method. 

Then add render() and return a canvas element nested in a division element.

Provide  <canvas /> with an id and attach React.createRef() to this element via the ref attribute. 

 

Add data to the ChartLine ClassComponent

react-chartjs > src > components > LineChart.js

import React, { Component } from 'react';
import Chart from 'chart.js/auto';

export default class LineChart extends Component {

	chartRef = React.createRef();

	componentDidMount() {
		const ctx = this.chartRef.current.getContext("2d");
		
		new Chart(ctx, {
			type: "line",
			data: {
				labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
				datasets: [{ 
					data: [86,114,106,106,107,111,133],
					label: "Total",
					borderColor: "#3e95cd",
					backgroundColor: "#7bb6dd",
					fill: false,
				}, { 
					data: [70,90,44,60,83,90,100],
					label: "Accepted",
					borderColor: "#3cba9f",
					backgroundColor: "#71d1bd",
					fill: false,
				}, { 
					data: [10,21,60,44,17,21,17],
					label: "Pending",
					borderColor: "#ffa500",
					backgroundColor:"#ffc04d",
					fill: false,
				}, { 
					data: [6,3,2,2,7,0,16],
					label: "Rejected",
					borderColor: "#c45850",
					backgroundColor:"#d78f89",
					fill: false,
				}
				]
			},
		});
	}
	render() {
		return (
			<div>
				<canvas
				id="myChart"
				ref={this.chartRef}
				/>
			</div>
			)
	}
}

With the initial file setup complete, we can add the chart's type and data.

Refer to How to use Chart.js to get examples of the different types of charts and customization options available. 

The React and Chart.js example above is a line chart. 

Feel free to pass in your own data via props rather than using the hard-coded values above.

 

Update App.js 

react-chartjs > src > App.js

import LineChart from "./components/LineChart.js";

export default function App() {
    return (
      <div>
        <LineChart />
      </div>
    );   
}

The last bit of configuration needed is done in App.js

Import the component LineChart from the components > LineChart.js file. 

Then export and declare the App functional component in one line.

Return <LineChart />.

Save the file.

 

React Chart.js Example in Browser

Browser window

Line Chart React and Chart.js

The last step, of course, is to see it rendered in the browser window. 

 






Post a Comment
Join the community

0 Comments
2
Jaysha
Written By
Jaysha
Hello! I enjoy learning about new CSS frameworks, animation libraries, and SEO.