DEV Community

Cover image for How to use Chart.js to create a Chart for Your Project
Ijay
Ijay

Posted on

How to use Chart.js to create a Chart for Your Project

Data visualization is a powerful tool for interpreting large and complex data sets. It involves creating graphical representations that give detailed information and can be used to generate insights into a given topic. It can be as simple as a graph or chart or as complex as an interactive dashboard with a variety of widgets and interactive elements.

The ability to see data in a visual format can aid in the identification of patterns and issues, as well as the discovery of correlations and relationships that are not immediately apparent when looking at raw data alone.

In this tutorial, I will be walking you through the process of building a chart utilizing chart.js within a React.js application.

prerequisite

  1. Have a basic understanding of the React.js framework.

  2. Install node.js on your system.

  3. Install Chart.js library and react-chartjs-2.

  4. Install Tailwindcss or any other CSS framework for styling your project.

What is Chart.js

Chart.js is a JavaScript library for creating charts and graphs on a web page. It allows developers to create charts such as bar charts, line charts, and pie charts.

The library uses the HTML5 canvas element to draw the charts, and it is designed to be highly customizable and easy to use. It also supports animation and interactive features. It's widely used and widely supported by many developers.

Why Should You Use Chart.js for Your Project?

Responsiveness: Chart.js is designed to be responsive and will automatically adjust the chart size to fit the available space.

Cross-browser compatibility: Chart.js is compatible with most modern web browsers, including recent versions of Chrome, Firefox, Safari, and Edge.

Animation: Chart.js also allows you to add some nice animations to the chart which makes them more engaging and interactive.

Open-source: Chart.js is an open-source library, which means that it is free to use and can be easily integrated into any project.

Customization: Chart.js offers a wide range of customization options, including different chart types, colors, and data labels.

Getting Started with Chart.js in React project

React-chartjs-2 provides various chart types for selection, such as Bar, Pie, and Line charts. Its React components have attributes, that are passed in as props to what is rendered.

To integrate Chart.js in a React project, you'll need to install the chart.js and react-chartjs-2 packages, which provide a React-friendly wrapper for the Chart.js library.

Here's an example of how you can get started:

npm install react-chartjs-2 chart.js --save
Enter fullscreen mode Exit fullscreen mode

Creating a Bar chart using chart.js

A bar chart is a graphical representation of data using rectangles, usually with heights or lengths proportional to the values they represent. They are commonly used to compare changes over time or differences between groups.

  • Import Bar from the react-chartjs-2 library into your React component.
import { Bar } from 'react-chartjs-2'
Enter fullscreen mode Exit fullscreen mode
  • Next, Import labels from Chart.js
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    Title,
    BarElement,
    Tooltip,
} from 'chart.js';
Enter fullscreen mode Exit fullscreen mode
  • Activate the labels by registering them such as tooltips. This will ensure that the labels are displayed when the user hovers over the chart data.
ChartJS.register(CategoryScale, LinearScale, Title, BarElement, Tooltip);
Enter fullscreen mode Exit fullscreen mode
  • Then, create a state object in your React component to store the data for the chart.

const state = {
    labels: [
        'JUNE',
        'JULY',
        'AUGUST',
        'SEPTEMBER',
        'OCTOBER',
        'NOVEMBER',
        'DECEMBER',
    ],
    // datasets  stored in an array of objects
    datasets: [
        {

            // you can set individual colors for each bar
            backgroundColor: ['red', 'green', 'pink', 'orange', 'yellow', 'lime'],
            hoverBackgroundColor: 'lightblue',
            borderRadius: 8,
            data: [40, 40, 50, 60, 80, 90, 70],
        },
    ],
};



export default BarChart

Enter fullscreen mode Exit fullscreen mode
  • Lastly, create a function that returns the JSX of the React component with the data you have made.
const BarChart = () => {
  return (
        <div>
            <h1 className="font-extrabold">sales for the month of JUNE-DECEMBER</h1>
          <Bar data={state} />
        </div>
    );
}

export default BarChart

Enter fullscreen mode Exit fullscreen mode

The result

bar
In addition to creating bar charts, the chart.js library also offers the ability to create other types of charts, such as pie charts and line charts.

Creating a Pie chart using chart.js

A pie chart is a circular chart that is divided into segments, or "slices," that display the proportion of different data values. Each segment represents a category of data, and the size of the segment corresponds to the magnitude of the data value for that category.

In comparison to a bar chart, a pie chart provides better visualization for showing the proportion of different data categories within the whole dataset.

  • Import the Pie from thereact-chartjs-2 library into your React component.
import { Pie } from 'react-chartjs-2'
Enter fullscreen mode Exit fullscreen mode
  • Import the pie chart labels from Chart.js
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'
Enter fullscreen mode Exit fullscreen mode

Activate the labels by registering them such as tooltips. This will ensure that the labels are displayed when the user hovers over the chart data.

ChartJS.register(ArcElement, Tooltip, Legend);
Enter fullscreen mode Exit fullscreen mode

Create a state object in your React component to store the data for the chart.

const state = {
    labels: [
        'JUNE',
        'JULY',
        'AUGUST',
        'SEPTEMBER',

    ],
    // datasets is an array of objects
    datasets: [
        {
            // you can set individual colors for each pie
            backgroundColor: ['purple', 'green', 'yellow', 'orange'],
            hoverBackgroundColor: 'lightblue',
            data: [40, 40, 50, 60],
        },
    ],
};
Enter fullscreen mode Exit fullscreen mode
  • Lastly, create a function that returns the JSX of the React component with the data you have made.
const Piechart = () => {
  return (
        <div>
            <h1 className='font-extrabold'>Pie chart representation of Sales from June-September</h1>
            <div style={{ width: '40%' }}>
                <Pie data={state} />
            </div>
        </div>
    );
}

Enter fullscreen mode Exit fullscreen mode

From the above code, the returned JSX is wrapped in another div; this is just for styling purposes to reduce the width.

The result

pie

Creating a Line chart using chart.js

A line chart is a graph made up of points connected by straight lines. It can be used to visualize changes in data over time and other types of data relationships.

  • Import Line from thereact-chartjs-2 library into your React component.
import { Line } from 'react-chartjs-2'
Enter fullscreen mode Exit fullscreen mode
  • Import Line chart labels from Chart.js
import {
    Chart as ChartJS,
    LineElement,
    CategoryScale, //x-axis
    LinearScale, //y-axis
    PointElement,
    Tooltip,
} from 'chart.js';

Enter fullscreen mode Exit fullscreen mode
  • Activate the labels by registering them such as tooltips. This will ensure that the labels are displayed when the user hovers over the chart data.
ChartJS.register(
    LineElement,
    CategoryScale,
    LinearScale,
    PointElement,
    Tooltip
);

Enter fullscreen mode Exit fullscreen mode
  • Create a state object in your React component to store the data for the chart.
const state = {
    labels: ['Lagos', 'Usa', 'Canada', 'Australia'],
    datasets: [
        {
            backgroundColor: ['blue', 'green', 'yellow', 'red'],
      data: [30, 4, -5, 37],
      borderColor: 'black',

        },
    ],
};

Enter fullscreen mode Exit fullscreen mode
  • Lastly, create a function that returns the JSX of the React component with the data you have made.
const Linechart = () => {
  return (
        <div>
            <div>
                <h1 className="font-extrabold">Temperature line chart</h1>
                <div style={{width: '50%' }}>
                    <Line data={state} />
                </div>
            </div>
        </div>
    );
}

export default Linechart

Enter fullscreen mode Exit fullscreen mode

From the above code, the returned JSX is wrapped in another div; this is just for styling purposes to reduce the width.

The result

line

Conclusion

Chart.js is an effective tool for creating various charts in React applications. However, we were only able to cover the most commonly used ones in this article.

The react-chartjs-2 package makes it easy to implement Chart.js charts in React applications by providing a set of React components that can be used to compose charts with just a few lines of code, making the process of creating charts in React applications very simple and easy.

Check out a project I created using char.js

Resource

You can find more information about Chart.js by reading through its official documentation. It covers the library's features, usage, and more.

Thanks for reading💖

Top comments (0)