Using React Chart.js to create interactive graphs

Using React Chart.js to create interactive graphs

Aryan Raj

7 min read | Published on : Jun 23, 2023

Last Updated on : May 15, 2024

Table of Contents

Data is an amazing story teller, and React charting libraries can help your present it in clear and captivating way on your React app.

Chart.js is a versatile library that excels at creating custom chart designs, resulting in rich, on-the-fly data visualizations. By combining React with Chart.js, developers can leverage these strengths to achieve dynamic chart displays that enhance user engagement and boost conversions.

In this article, we'll explore how to install Chart.js in a React application, delve into the core principles of Chart.js, and learn how to create various types of charts, including line, bar, and pie charts, using React components.

We'll also cover how to customize the appearance of your charts to align with your application's style and design, and how to use React to add animations and interactivity to your charts. Let's dive in and discover how to use Chart.js with React to create stunning data visualizations!

Installing Chart.js in React

Before you start integrating Chart.js into React projects, it’s important to ensure that we have the essential tools installed.

Open your terminal and run the command to install these libraries.

npm install chart.js react-chartjs-2

React-chartjs-2 is a React wrapper for Chart.js 2.0 and 3.0 that allows us to use Chart.js elements as React components.

In this post, we will use improvised data to create three different charts that depict the amount of users gained in an organisation.

Creating different types of charts

We will generate various React components for charts for the sake of convenience and explore some examples of charts.

1. Creating line chart with Chart.js

The first step when seeking to create a line chart in your React application is generating a fresh directory named as "components."

Next, create a file located within this folder titled "LineChart.js." Use import with Chart.js and react-chartjs-2 in your LineChart.js file soon.

A line chart requires labels to name each data point along the x-axis and y-axis. These labels are usually provided as props to the chart component. In addition to the labels, line charts also require data as props to display the information on the graph.

The data prop contains datasets that holds various properties of the chart, such as the height, width, and color of the lines. You can edit these datasets to customize the appearance of the line chart, including changing the backgroundColor and borderColor. Here’s an example:

import React from "react"; // Importing the React library
import Chart from "chart.js/auto"; // Importing the Chart.js library
import { Line } from "react-chartjs-2"; // Importing the Line component from the react-chartjs-2 library

// Setting up the labels for the x-axis of the chart
const labels = ["January", "February", "March", "April", "May", "June"];

// Setting up the data for the chart, including the labels and datasets
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],
    },
  ],
};

// Defining the LineChart component
const LineChart = () => {
  return (
    <div>
      <Line data={data} />
    </div>
  );
};

export default LineChart; // Exporting the LineChart component as the default export of the module

The example code showcased above is an instance of a simple line chart that can be subsumed within a React application through its corresponding file - LineChart.js.

2. Creating a bar chart with Chart.js

Similarly, we can work with a Bar Chart in Chart.js. Here’s an example:

// ./components/BarChart.js

// Import the React library.
import React from "react";

// Import the Chart.js library.
import Chart from "chart.js/auto";

// Import the Bar component from the react-chartjs-2 library.
import { Bar } from "react-chartjs-2";

/**
 * Define a functional component named BarChart
 */
const BarChart = () => {
  // Define an array of labels.
  const labels = ["January", "February", "March", "April", "May", "June"];

// Defined an object
  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],
      },
    ],
  };

// Return the Bar component, passing in the data object as a prop.
  return (
    <div>
      <Bar data={data} />
    </div>
  );
};

// Export the BarChart component as the default export of the module.
export default BarChart;

3. Creating a pie chart with Chart.js

Pie chart implementation is no different, and we may use a comparable method to do so. Let’s understand the implementation using an example:

// ./components/PieChart.js

import React from "react"; // Import the necessary library such as React for now.
import Chart from "chart.js/auto"; // Import the Chart.js library.
import { Pie } from "react-chartjs-2"; // In the react-chartjs-2 library, import the Pie component.

// Define an array of labels.
const labels = ["January", "February", "March", "April", "May", "June"];

// Defined an object.
const data = {
  labels: labels,
  datasets: [
    {
      label: "My First dataset",
      backgroundColor: "rgb(255, 99, 132)",
      borderColor: "rgb(0,0,255)",
      data: [0, 10, 5, 2, 20, 30, 45],
    },
  ],
};

/**
 * Define a functional component named PieChart
 * that returns a Pie component from react-chartjs-2,
 */
const PieChart = () => {
  return (
    <div>
      <Pie data={data} />
    </div>
  );
};

// PieChart component is exported as default module.
export default PieChart;
import React from "react";
import BarChart from "./components/BarChart";
import LineChart from "./components/LineChart";
import PieChart from "./components/PieChart";

function App() {
  return (
    <div>
      <h1>Charts Example</h1>
      <div className="chart-container">
        <BarChart />
        <LineChart />
        <PieChart />
      </div>
    </div>
  );
}

export default App;

Passing static data into Charts

Incorporating a pie chart that depicts static data for top-liked React libraries is possible by updating your PieChart.js file's data object with this code:

const labels = [
  "React Router",
  "Redux",
  "React Native",
  "Material UI",
  "Next.js",
  "Gatsby",
];

const data = {
  labels: labels,
  datasets: [
    {
      label: "Best React charting libraries",
      backgroundColor: [
        "#00A6B4",
        "#2E4057",
        "#FFD662",
        "#DD1C1A",
        "#FF8600",
        "#0E2F44",
      ],
      borderColor: "#fff",
      borderWidth: 1,
      hoverBackgroundColor: [
        "#003e4f",
        "#4c5b5c",
        "#946c2f",
        "#6b0f12",
        "#b25800",
        "#041f2b",
      ],
      hoverBorderColor: "#000",
      data: [30, 25, 20, 15, 5, 5],
    },
  ],
};

const PieChart = () => {
  return (
    <div>
      <Pie data={data} />
    </div>
  );
};

export default PieChart;

Passing dynamic data to charts

Building upon our ability to demonstrate static data on visual aids, let us proceed towards understanding how we may incorporate real-time updates into charts.

Assume that we desire producing a line chart illustrating hourly signups for new website users. Utilizing libraries such as  socket.io , connecting them with servers allows us to receive real-time statistics which immediately displays on charts via tools such as the Chart.js API.

The code below uses functions like setInterval() to update the data every minute. This keeps the information fresh and the users interested. You can see an example of using soccket.io() and Chart.js() for this.

import React, { useEffect, useState } from 'react';
import Chart from 'chart.js/auto';
import io from 'socket.io-client';

const socket = io('http://localhost:3000'); // replace with your server URL

const LineChart = () => {
  const [data, setData] = useState([]);

useEffect(() => {
    socket.on('newUser', (newUser) => {
      setData(prevData => [...prevData, newUser]);
    });
  }, []);

useEffect(() => {
    const ctx = document.getElementById('myChart').getContext('2d');
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['12:00 PM', '1:00 PM', '2:00 PM', '3:00 PM', '4:00 PM', '5:00 PM', '6:00 PM'],
        datasets: [
          {
            label: 'New Users',
            data: data,
            borderColor: 'rgb(255, 99, 132)',
            backgroundColor: 'rgba(255, 99, 132, 0.2)',
            borderWidth: 1,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true,
              },
            },
          ],
        },
      },
    });

const interval = setInterval(() => {
      chart.update();
    }, 60000);

return () => clearInterval(interval);
  }, [data]);

return (
    <div>
      <canvas id="myChart" width="400" height="400"></canvas>
    </div>
  );
};

export default LineChart;

Conclusion

Chart.js is a popular React Charting library, that helps in creating customizable and interactive charts and graphs in web applications. It has many helpful APIs for React, that makes it easy to create and change charts in components.

Chart.js allows you to create a variety of charts such as scatterplots, bar charts, line charts, and pie charts. These charts can be used to compare, correlate, distribute, or display the composition of your data. One of the key advantages of Chart.js is its ability to handle both static and dynamic data.

Before we conclude, here are some compelling reasons to use Chart.js for creating interactive charts:

Feel free to refer to the code we've shared to create different types of charts with Chart.js. Happy coding!