Using React Chart.js to create interactive graphs

Zipy team - Jan 3 - - Dev Community

Image description

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 one such library, that boosts versatility when it comes to developing custom chart designs resulting in rich data visualizations on-the-fly. Using React and Chart.js concurrently, it allows developers to take advantage of these strengths; accomplishing dynamic chart displays that positively impact engagement and increase conversion.

In this article, we will cover how you can install Chart.js into React, dive into the principles of Chart.js, and learn how to use React components to create various sorts of charts such as line, bar, pie, and more.

We will also learn how to make charts look more appealing and fit your application’s style and design, and how to use React to add animations and interactivity to your charts. So, let's get started and learn how to use Chart.js in 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
Enter fullscreen mode Exit fullscreen mode

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", // Setting up the label for the dataset
      backgroundColor: "rgb(255, 99, 132)", // Setting up the background color for the dataset
      borderColor: "rgb(255, 99, 132)", // Setting up the border color for the dataset
      data: [0, 10, 5, 2, 20, 30, 45], // Setting up the data for the dataset
    },
  ],
};

// Defining the LineChart component
const LineChart = () => {
  return (
    <div>
      <Line data={data} /> // Rendering the Line component from the react-chartjs-2 library with the data passed as props
    </div>
  );
};

export default LineChart; // Exporting the LineChart component as the default export of the module
Enter fullscreen mode Exit fullscreen mode

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.

This file is located within the 'components' folder residing inside our application's directory.
To execute this implementation seamlessly, it is vital to ensure that all required libraries pertaining to it are imported at its inception.
It's essential here that you receive accurate chart interpretations due entirely upon keen attention being applied in passing data via properly formatted props prior to utilizing our LineChart component.

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;
Enter fullscreen mode Exit fullscreen mode
  • At the beginning of the file, Chart.js and Bar components are imported from react-chartjs-2 library
  • In addition to this functional component, BarChart definition has been created which further return Bar Component as its output to render successive bar charts.
  • The above code creates an object called data that has information about the dataset, such as backgroundColor, borderColor, label, and and data.
  • This BarChart Component passes data object as prop while returning resulting Bar chart using simplified but unique implementation utilized in given scenario.
  • In the end BarChart component is being exported as default export of this module using export default statement to make it importable and useful in various other different modules out there.

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;
Enter fullscreen mode Exit fullscreen mode
  • This code has a function called PieChart that makes pie charts with Chart.js and ReactJS.
  • It uses two arrays: labels for the names of the slices and data for the values of the slices. It also has some options for the colors and borders of the slices.
  • The function returns a PieChart component that uses props from data.
  • To use this function in other files, export it as the default and import it with import {PieChart} from "react-chartjs-2".
  • You can also import other chart types like import {BarChart} from "react-chartjs-2" or import {LineChart} from "react-chartjs-2".
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;
Enter fullscreen mode Exit fullscreen mode
  • To render three components namely: BarChart, LineChart, and PieChart, their import statements are specified in the code for App.js .
  • Also, when these widgets are exported, they are placed inside a div with the class name chart-container and specified as the App(){} function.
  • Lastly, to enable its global usage in other files, this module exports App(), as its default export.

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;
Enter fullscreen mode Exit fullscreen mode
  • To simplify designing concerning popular React libraries, the code sets up an array named as labels comprising specific library names.
  • Secondly, a new object consisting other two sub-arrangements namely datasets and labels, known as data.
  • These purposefully constructed datasets includes multiple core properties such as backgroundColor, hoverBackgroundColor, borderColor and one more vital key described merely as data.
  • Now, the code sets two properties: backgroundColor and hoverBackground colors. It has arrays with different colors for each library.
  • The remainder property viz., data centrally manages yet another list holding necessary percentages corresponding to respective libraries.
  • Eventually, the code uses a prop called Pie and a data-object with the lists from labels and datasets. This makes the PieChart component.

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;
Enter fullscreen mode Exit fullscreen mode

This example displays how we connect to a server using socket.io-client , responding to every occurrence of a newUser event by modifying our state with new user counts. But in the provided code, the reading is captured at a time interval of 1 minute (60,000 milliseconds).

Here, integration makes use of two different instances where we invoke hooks:

  • First and foremost, an instance of useEffect ensures that our socket connection is established and running adequately while receiving incoming data.
  • Secondarily another instance runs whenever incoming data requires amending our chart in real-time, subsequently producing updated charts promptly when changes occur.
  • Lastly, we adopted setInterval control function which enables us to renew essential data within intervals as low as possible say after every minute.

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.

This tool can make different charts like scatterplots, bar, lines, or pies charts. You can use these charts to compare, correlate, distribute, or show the composition of your data. The good thing about Chart.js is, it works for both static and dynamic data.

Before we wind up, here are some reasons you should consider Charts.js to create interactive charts:

  • It is easy to use and customize with React
  • It supports many types of charts and animations
  • It is responsive and fast
  • It is free and open source
  • You can also refer to the code we have shared, to create different types of charts with Charts.js.

Happy Coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player