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.
npx create_react_app my_react_app
npm install --save react-chartjs-2 chart.js
or
yarn add react-chartjs-2 chart.js
Line
graph from Chart.js in the following manner.import { Line } from "react-chartjs-2";
x
and y axis
values in the Line
component 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 graphHere 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.