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,
BarElement,
CategoryScale,
LinearScale,
Tooltip,
Legend
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
BarElement: the bar 'component'
CategoryScale: the x-axis of the graph
LinearScale: the y-axis dataset of the graph
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, CategoryScale, LinearScale, Tooltip, Legend );
3 - Paasing the data to the Bar component
Create constants called data and options and input all the datasets for the bar graph.
const data = {
labels: ['Jan', 'Feb', 'Mar', "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Nov", "Dec"],
datasets: [
//Bar-1 Data set
{
label: 'Roller Shades',
data: [4, 6, 4],
backgroundColor: 'aqua',
borderColor: 'black',
borderWidth: 1
},
//Bar-2 Data set
{
label: 'Zebra Blinds',
data: [8, 3, 5],
backgroundColor: 'green',
borderColor: 'black',
borderWidth: 1
}
]
}
const options = {}
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
Pass the value to the Bar component:
<>
<Bar
data={data}
options={options}
/>
</>