How to create a React Chart.js line graph app
In this shot, we will use the Chart.js library to create a simple Line Graph application in React and plot the weekly results of our daily calories lost.
You can read more information about React Chart.js here.
- First, we use the following command to create a React application.
npx create_react_app my_react_app
- Next, we perform necessary clean-up, which includes the removal of the logo.svg and tests file from the src folder of our app. Now, we need to install two dependencies in order to make use of Chart.js in React. To do this, we run the following command.
npm install --save react-chartjs-2 chart.js
or
yarn add react-chartjs-2 chart.js
- After the dependencies are installed, we create a LineGraph.js file in the src folder where we will write the code for our graph. In this file, we will need to import the
Linegraph from Chart.js in the following manner.
import { Line } from "react-chartjs-2";
- Next, we will define the
xandy axisvalues in theLinecomponent as follows:
<Line
data={{
// x-axis label values
labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
datasets: [
{
label: "# of Calories Lost",
// y-axis data plotting values
data: [200, 300, 1300, 520, 2000, 350,150],
fill: false,
borderWidth:4,
backgroundColor: "rgb(255, 99, 132)",
borderColor:'green',
responsive:true
},
],
}}
/>
Below is the description of all the corresponding values in the data object:
label: values on the x-axisdata: array to be plotted over the y-axisfill:false: if you want your graph to be filled underneath the plotted points then you will set the fill to trueborderColor: color of the line that is plotted on the graphborderWidth: width of the line graph
LineGraph.js
Here is the complete LineGraph.js file:
import React from "react";
import { Line } from "react-chartjs-2";
function LineGraph() {
return (
<div>
<Line
data={{
// x-axis label values
labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"],
datasets: [
{
label: "# of Calories Lost",
// y-axis data plotting values
data: [200, 300, 1300, 520, 2000, 350,150],
fill: false,
borderWidth:4,
backgroundColor: "rgb(255, 99, 132)",
borderColor:'green',
responsive:true
},
],
}}
/>
</div>
);
}
export default LineGraph;
Use nmp start to run this app, and you will find a beautiful, responsive line graph plotted across the x and y-axis.

We demonstrated a very simple implementation of Chart.js. It can, however, be used for a variety of purposes, wherever you are using a variety of data values.