Package dependencies:
Chart.js: Among many charting libraries for JavaScript application developers, Chart.js is currently the most popular one according to GitHub stars (~60,000) and npm downloads (~2,400,000 weekly).
pnpm add react-chartjs-2 chart.js
# or
yarn add react-chartjs-2 chart.js
# or
npm i react-chartjs-2 chart.js
1 - Importing the libraries that require to make a Line Chart
import {
Chart as ChartJS,
LineElement,
PointElement,
CategoryScale,
LinearScale,
Tooltip,
Legend
} from 'chart.js';
import { Line } from 'react-chartjs-2';
LineElement: the line 'component'
CategoryScale: the x-axis of the graph
LinearScale: the y-axis dataset of the graph
PointElement: the dots in the line, also known as the datapoint
ToolTip: a graphical UI element that provides extra information as we hover the mouse over the chart elements
Legend: displays data about the datasets that appear on the chart.
More info about components: Tutorial Spot
Chart JS documentation: chartjs
2 - Initialization of the properties
Registering the properties inside the ChartJS function
ChartJS.register( LineElement, PointElement, CategoryScale, LinearScale, Tooltip, Legend );
3 - Paasing the data to the Line component
Create an object called data,
const data = {
labels: ['Jan', 'Feb', 'March'],
datasets: [{
label: 'Month',
data: [50, 60, 70],
borderColor: 'aqua',
tension: 0.4
}]
};
The values inside the data object are:
labels: contains the values for the x-axis
datasets[label]: this is the label identifier
data: line graph data
borderColor: the line colour
tension: the line curviness
Creating the <Line> component inside the return.
return (
<div className='col-12'>
<Line
data={data}
></Line>
</div>
);
Then passing the data prop inside the Line component. That's it then the line chart is ready to use😏.