How to install and use chart.js in react js?
April 14, 2023Hi Friends 👋,
Welcome To aGuideHub!
To install and use chart.js in React js, you have to use the npm
package manager that is how you can install the chart.js
library into your project.
Today, I am going to show you, how to install and use chart.js in react js.
install and use chart.js
Install the following packages to use chart.js
in react js.
npm
npm install --save react-chartjs-2 chart.js
Table of contents
- Set up the React project.
- Import necessary components.
- Use chart.js.
Step 1: Set up the React project.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import necessary components.
After installing chart.js
, you have to import your React component. To do this, add the following line to the top of your component file.
import React from "react";
import Chart from "chart.js/auto";
import { Line } from "react-chartjs-2";
Step 3: Use chart.js.
We can edit datasets
to change backgroundColor
, borderColor
, etc of graph.
<div>
<Line data={data} />
</div>
React chart.js example.
The code below is an example of this, All charts require labels to name each bar on the graph
, and it takes data as props
to display information on the graph.
App.js
import React from "react";
import Chart from "chart.js/auto";
import { Line } from "react-chartjs-2";
const labels = ["January", "February", "March", "April", "May", "June"];
const data = {
labels: labels,
datasets: [
{
label: "My First dataset",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45],
},
],
};
const LineChart = () => {
return (
<div>
<Line data={data} />
</div>
);
};
export default LineChart;
Check the output of the above code example.
Here, we are provided code sandbox links for the above program install and use chart.js in React js. Then you can use whenever you went and do the changes as per your requirements.
All the best 👍