Using React Chart.js to create interactive graphs

Aryan Raj
7 min read | Published on : May 15, 2024
Last Updated on : Jul 30, 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", // 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

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.

Take React debugging to the next level, with AI assistance. Join Zipy!

Get Started for free

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;
  • 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;
    
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;
  • 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.

Take React debugging to the next level, with AI assistance. Join Zipy!

Get Started for free

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;
  • 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;

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.

Take React debugging to the next level, with AI assistance. Join Zipy!

Get Started for free

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:

  • Ease of Use: Simple to use and customize with React.
  • Variety: Supports a wide range of chart types and animations.
  • Performance: Responsive and fast.
  • Cost: Free and open-source.

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

Wanna try Zipy?

Zipy provides you with full customer visibility without multiple back and forths between Customers, Customer Support and your Engineering teams.

The unified digital experience platform to drive growth with Product Analytics, Error Tracking, and Session Replay in one.

product hunt logo
G2 logoGDPR certificationSOC 2 Type 2
Zipy is GDPR and SOC2 Type II Compliant
© 2024 Zipy Inc. | All rights reserved
with
by folks just like you