Chinwike Maduabuchi Frontend developer passionate about software engineering.

Using Chart.js in React

4 min read 1242

Using Chart.js in React

Editor’s note: This React Chart.js tutorial was last updated on 18 November 2022 to add information on the PieChart and LineChart types in Chart.js.

Data visualization has always been an important part of software engineering and frontend development in particular. There’s always a need to visualize data for our users to help them better understand what is going on in our application.

Chart.js is a popular JavaScript library used for creating flexible charts on websites, and in this tutorial, you’ll learn how to use Chart.js in a React environment.

We’ll cover:

Prerequisites

To follow along, you’ll need a basic understanding of the React framework. React’s documentation is a good place to start.

Installing Chart.js in a React project

I’ll be using CodeSandbox to set up a new React app but you can choose to set up a React application with whichever tool you’re comfortable with. The project’s Sandbox is available here.

To create a fresh React template in CodeSandbox, open a new tab in your browser and type in react.new.

Next, in the dependencies section, add these two libraries:

  • chart.js
  • react-chartjs-2

If you’re working from the terminal, you can install these libraries with the following command:

npm install chart.js react-chartjs-2

React-chartjs-2 is a React wrapper for Chart.js 2.0 and 3.0, letting us use Chart.js elements as React components.

In this post, we will create three charts that delineate the number of users gained in a company with makeshift data.

Creating the makeshift data

From the file tree, create a utils folder and store a Data.js file. Here, we’ll store the data and export it to a separate component for rendering the chart.

Input the contents of Data.js with the code below:

// utils/Data.js
export const Data = [
  {
    id: 1,
    year: 2016,
    userGain: 80000,
    userLost: 823
  },
  {
    id: 2,
    year: 2017,
    userGain: 45677,
    userLost: 345
  },
  {
    id: 3,
    year: 2018,
    userGain: 78888,
    userLost: 555
  },
  {
    id: 4,
    year: 2019,
    userGain: 90000,
    userLost: 4555
  },
  {
    id: 5,
    year: 2020,
    userGain: 4300,
    userLost: 234
  }
];

You can now import this data and feed it to a Chart.js component to present it. But before we do that, let’s understand the API of the component in the react-chartjs-2 package.

Chart.js React components

react-chartjs-2 offers a variety of chart types to select from. These include Bar, Radial, Pie, etc. The React components from this package accept a number of props, the two main ones being data and options.

The data prop takes in an object similar to the one below:

const data = {
        labels: ['Red', 'Orange', 'Blue'],
        // datasets is an array of objects where each object represents a set of data to display corresponding to the labels above. for brevity, we'll keep it at one object
        datasets: [
            {
              label: 'Popularity of colours'
              data: [55, 23, 96],
              // you can set indiviual colors for each bar
              backgroundColor: [
                'rgba(255, 255, 255, 0.6)'
                'rgba(255, 255, 255, 0.6)'
                'rgba(255, 255, 255, 0.6)'
              ],
              borderWidth: 1,
            }
        ]
}

backgroundColor and borderWidth are just some of the properties that can be added to the datasets array. View the full list of acceptable proprieties here.

Now that we know how the data object is set up, you can populate it with data from the Data.js file.

Creating a Chart.js pie chart

In App.js, we will replicate the schema for the data prop in a chartData variable created using the useState Hook.

The labels and dataset array can be populated with our makeshift data by using the JavaScript map method. Edit App.js with the following code:

// App.js
import { useState } from "react";
import { Data } from "./Data";
import "./styles.css";

export default function App() {
  const [chartData, setChartData] = useState({
    labels: Data.map((data) => data.year), 
    datasets: [
      {
        label: "Users Gained ",
        data: Data.map((data) => data.userGain),
        backgroundColor: [
          "rgba(75,192,192,1)",
          "#ecf0f1",
          "#50AF95",
          "#f3ba2f",
          "#2a71d0"
        ],
        borderColor: "black",
        borderWidth: 2
      }
    ]
  });

  return (
    <div className="App">
      <p>Using Chart.js in React</p>
    </div>
  );
}

What we’ve done above is prepare the data we want to represent on different charts in an object named chartData. This state can then be passed to a PieChart component, which will render a pie chart.



Create a components folder in src and create an empty PieChart.js that you will import as such:

// App.js
import { useState } from "react";
import { Data } from "./Data";
import PieChart from "../components/PieChart";
import "./styles.css";

export default function App() {
  const [chartData, setChartData] = useState({
    // ...chart data
  });

  return (
    <div className="App">
      <PieChart chartData={chartData} />
    </div>
  );

The contents of PieChart.js will look like this:

// src/components/PieChart.js
import React from "react";
import { Pie } from "react-chartjs-2";

function PieChart({ chartData }) {
  return (
    <div className="chart-container">
      <h2 style={{ textAlign: "center" }}>Pie Chart</h2>
      <Pie
        data={chartData}
        options={{
          plugins: {
            title: {
              display: true,
              text: "Users Gained between 2016-2020"
            }
          }
        }}
      />
    </div>
  );
}
export default PieChart;

Here, we’ve imported the Pie React component from react-chartjs-2. The chartData is destructured and passed Pie’s data prop. I’ve also used the options object to tweak certain aspects of the chart, like the chart title and legend. Check out all the configurable options.

This should render the chart below:

Chart.js Pie Chart

Creating a Chart.js bar chart

Create a BarChat component and input the following code:

// components/BarChart.js
import { Bar } from "react-chartjs-2";
export const BarChart = ({ chartData }) => {
  return (
    <div className="chart-container">
      <h2 style={{ textAlign: "center" }}>Bar Chart</h2>
      <Bar
        data={chartData}
        options={{
          plugins: {
            title: {
              display: true,
              text: "Users Gained between 2016-2020"
            },
            legend: {
              display: false
            }
          }
        }}
      />
    </div>
  );
};

Now import this component into App.js:

// App.js
import { useState } from "react";
import { Data } from "./Data";
import PieChart from "../components/PieChart";
import BarChart from "../components/BarChart";
import "./styles.css";

export default function App() {
  const [chartData, setChartData] = useState({
    // ...chart data
  });

  return (
    <div className="App">
      <PieChart chartData={chartData} />
      <BarChart chartData={chartData} />
    </div>
  );

This will render the bar chart below:

Chart.js Bar Chart

Creating a Chart.js line chart

For the line chart, create a LineChart component, just as we did for the previous two cases, and edit it with the following content:

// components/LineChart.js
import React from "react";
import { Line } from "react-chartjs-2";
function LineChart({ chartData }) {
  return (
    <div className="chart-container">
      <h2 style={{ textAlign: "center" }}>Line Chart</h2>
      <Line
        data={chartData}
        options={{
          plugins: {
            title: {
              display: true,
              text: "Users Gained between 2016-2020"
            },
            legend: {
              display: false
            }
          }
        }}
      />
    </div>
  );
}
export default LineChart;

Next, import this component into App.js:

// App.js
import { useState } from "react";
import { Data } from "./Data";
import PieChart from "../components/PieChart";
import BarChart from "../components/BarChart";
import LineChart from "../components/LineChart";
import "./styles.css";

export default function App() {
  const [chartData, setChartData] = useState({
    // ...chart data
  });

  return (
    <div className="App">
      <PieChart chartData={chartData} />
      <BarChart chartData={chartData} />
      <LineChart chartData={chartData} />
    </div>
  );

And that wraps up our project! The above configurations will render the line chart below:

Chart.js Line Chart

Conclusion

Chart.js is a powerful tool for creating different types of charts in web applications. You’ve also seen how helpful the react-chartjs-2 package is for rendering these charts in React. I encourage you to visit the Chart.js documentation to learn more about the library and delve into the options object to see more ways to configure your charts.

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Chinwike Maduabuchi Frontend developer passionate about software engineering.

Leave a Reply