Create Stunning Charts with React Using Chart.js

Chart.js is an open-source JavaScript library used to create interactive and visually appealing charts for the web.

It is an extremely powerful and flexible tool for displaying data in a variety of formats, and can be easily implemented in a React project to create a dynamic and engaging user experience.

The popularity of chart.js is due to its user-friendly nature and its ability to quickly render charts with minimal coding. In this blog post, we will discuss chart.js and its benefits when added to a React project.

We will also explore how to implement chart.js in React, discuss some of the pit falls of chart.js, and provide some helpful tips and tricks to make the most of chart.js within your project.

By the end of this post, you should have a better understanding of what chart.js can do for your React project, and the knowledge to successfully implement it.

  1. What is Chart JS in React?
  2. Why Chart.js?
  3. How can I use Chart.js in a React application?
  4. Components of Chart.js React
  5. Passing data to a Chart.js component in React
  6. How do I change the type of chart (e.g. from bar to line) in a Chart.js component in React?

What is Chart JS in React?

To begin with, React is a Java script-based UI library. It is library rather than a language and is primarily used for web development. This library is used for building user interfaces and modern applications.

Chart.js is a Java Script library which is used for creating charts on websites. It is one of the libraries available for creating charts in React and it is easy to use.

Moreover, chart.js supports 8 different types of responsive charts. Once you set up your chart, chart.js will do the responsive jobs and make it legible. In addition, chart.js graphs are customizable.

Why Chart.js?

Chart.js is used for the following benefits:

  • Easy to use
  • Best documentation facilities
  • Simple visualization library
  • Helps in creating flexible charts
  • Well maintained library

Data visualization is an essential part of software development since it helps you to communicate better with the end users. Moreover, visualizing data helps the users to understand better.

How can I use Chart.js in a React application?

To use Chart.js in a React application, you can use the react-chartjs-2 package, which allows you to use Chart.js as a component in your React code. First, you will need to install the package using npm or yarn:

npm install react-chartjs-2 chart.js

or

yarn add react-chartjs-2 chart.js

Then, you can import the Chart component from the react-chartjs-2 package and use it in your React code like any other component. For example:

import React from 'react';
import { Line } from 'react-chartjs-2';

const data = {
  labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  datasets: [
    {
      label: 'JavaScript Errors',
      fill: false,
      lineTension: 0.1,
      backgroundColor: 'rgba(245,39,39,0.8)',
      borderColor: 'rgba(245,39,39,0.8)',
      borderCapStyle: 'butt',
      borderDash: [],
      borderDashOffset: 0.0,
      borderJoinStyle: 'miter',
      pointBorderColor: 'rgba(245,39,39,0.8)',
      pointBackgroundColor: '#fff',
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHoverBackgroundColor: 'rgba(245,39,39,0.8)',
      pointHoverBorderColor: 'rgba(220,220,220,1)',
      pointHoverBorderWidth: 2,
      pointRadius: 1,
      pointHitRadius: 10,
      data: [5, 6, 7, 8, 6, 5, 3]
    }
  ]
};

function App() {
  return (
    <div>
      <Line data={data} width={75} height={25} />
    </div>
  );
}
export default App;

You can also pass options property to the Chart component to customize the appearance and behavior of the chart.

Note that you need to import chart.js library in addition to react-chartjs-2 package to use the Chart component in your React application.

Components of Chart.js React

React Chart.js offers a variety of charts to choose the following are the list of charts:

Components of Chart.js React
Components of Chart.js React

The main props being accepted by the React components are data and options. Some of the properties are background Color, border Width, etc. Now we shall see some basic charts and their codes in react


Passing data to a Chart.js component in React

To pass data to a Chart.js component in a React application, you can pass a data prop to the component. The data prop should contain an object with properties for the chart's data and options.

For example, you can pass data to a Chart.js component like this:

import { Bar } from 'react-chartjs-2';

function MyChart() {
  const data = {
    labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    datasets: [
      {
        label: 'My First dataset',
        backgroundColor: 'rgba(255,99,132,0.2)',
        borderColor: 'rgba(255,99,132,1)',
        borderWidth: 1,
        hoverBackgroundColor: 'rgba(255,99,132,0.4)',
        hoverBorderColor: 'rgba(255,99,132,1)',
        data: [65, 59, 80, 81, 56, 55, 40]
      }
    ]
  };

  return (
    <div>
      <Bar
        data={data}
        width={100}
        height={50}
        options={{ maintainAspectRatio: false }}
      />
    </div>
  );
}

In this example, the data prop contains an object with properties for the chart's labels and datasets. The labels property contains an array of strings that will be used as the labels for the chart, and the datasets property contains an array of objects that define the data for the chart.

Each object in the datasets array should have properties for the label, background color, border color, border width, hover background color, hover border color and data.

You can also pass options property to the Chart component to customize the appearance and behavior of the chart.

How do I Change the Chart Type

To change the type of chart in a Chart.js component in a React application, you can update the options prop of the component with a new value for the type property.

For example, if you want to change a Pie chart to a Bar chart, you can update the options prop like this:

import React from 'react';
import { Pie } from 'react-chartjs-2';
import { Chart, ArcElement } from 'chart.js';
Chart.register(ArcElement);

const data = {
  labels: [
    'Desktop',
    'Mobile',
    'Tablet'
  ],
  datasets: [{
    label: 'New dataset',
    data: [300, 50, 100],
    backgroundColor: [
      'rgb(250, 242, 150)',
      'rgb(150, 250, 153)',
      'rgb(150, 245, 250)'
    ],
    hoverOffset: 4
  }]
};
const PieChart = () => {
  return (
    <div>
      <Pie data={data} width={75} height={25} />
    </div>
  );
};
export default PieChart;

You can also change the type of chart by simply changing the imported component at the top of the file. For example, if you want to use a Pie chart, you can import like this:

Before:

import { Pie } from 'react-chartjs-2';

To:

import { Bar } from 'react-chartjs-2';

also don't forget this part in your JSX as well.

Before:

<Pie data={data} />

To:

<Bar data={data} />

Before:

change-chart-in-chartjs-in-react
change-chart-in-chartjs-in-react

After:

change-chart-in-chartjs-in-react
change-chart-in-chartjs-in-react-2

You can change the type of chart by replacing the component imported from the react-chartjs-2 package with any other chart type, such as Line, Radar, Polar, etc.., that only comes under chart-js

Additionally, you can also use options prop to configure and customize the behavior and appearance of the chart. For example, you can use options property to change the type of chart dynamically by updating the options prop with a new value for the type property.

Other Chart.js Examples

1. Line chart

Follow the below steps:

  1. Create new folder called Components.
  2. Create a new filled called Linechart.js and add the below code:

Code:

import React from 'react';
import { Line } from 'react-chartjs-2';

const data = {
  labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
  datasets: [
    {
      label: 'Total Session of My Website',
      fill: false,
      lineTension: 0.1,
      backgroundColor: 'rgba(75,192,192,0.4)',
      borderColor: 'rgba(75,192,192,1)',
      borderCapStyle: 'butt',
      borderDash: [],
      borderDashOffset: 0.0,
      borderJoinStyle: 'miter',
      pointBorderColor: 'rgba(75,192,192,1)',
      pointBackgroundColor: '#fff',
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHoverBackgroundColor: 'rgba(75,192,192,1)',
      pointHoverBorderColor: 'rgba(220,220,220,1)',
      pointHoverBorderWidth: 2,
      pointRadius: 1,
      pointHitRadius: 10,
      data: [650, 590, 800, 810],
    },
  ],
};

function App() {
  return (
    <div>
      <Line data={data} width={75} height={25} />
    </div>
  );
}
export default App;

Output:

2. Bar chart

Code:

import { Bar } from 'react-chartjs-2';
import { Chart, registerables } from 'chart.js';
import React from 'react';

function MyChart() {
  Chart.register(...registerables);
  const data = {
    labels: [
      'Week 1',
      'Week 2',
      'Week 3',
      'Week 4',

    ],
    datasets: [
      {
        label: 'Website View January',
        backgroundColor: '#ff84b5 ',
        borderColor: '#ff5197',
        borderWidth: 1,
        hoverBackgroundColor: '#ff5197',
        hoverBorderColor: '#ff5197',
        data: [650, 590, 800, 810],
      },
    ],
  };

  return (
    <div>
      <Bar data={data} width={75} height={25} />
    </div>
  );
}

export default MyChart;

Output:

chartjs-in-react-bar-chart
chartjs-in-react-bar-chart

3. Pie Chart

Code:

import React from 'react';
import { Pie } from 'react-chartjs-2';
import { Chart, ArcElement } from 'chart.js';
Chart.register(ArcElement);

const data = {
  labels: [
    'Desktop',
    'Mobile',
    'Tablet'
  ],
  datasets: [{
    label: 'New dataset',
    data: [300, 50, 100],
    backgroundColor: [
      '#c46d92',
      '#843657',
      '#481d2f'
    ],
    hoverOffset: 4
  }]
};
const PieChart = () => {
  return (
    <div>
      <Pie data={data} width={75} height={25} />
    </div>
  );
};
export default PieChart;

Output:

chartjs-in-react-pie-chart
chartjs-in-react-pie-chart

Importing components

The final step is to import these components in to App.js file. The code for it is as follows:

import BarChart from "./components/BarChart";
import LineChart from "./components/LineChart";
import PieChart from "./components/PieChart";
function App() {
 return (
  <div>
   <LineChart />
   <BarChart />
   <PieChart />
  </div>
 );
}

export default App;

Conclusion

Chart.js is a free and open-source JavaScript library for creating responsive and customizable charts. It offers various chart types, including line, bar, pie, doughnut, and more. Chart.js is easy to use and provides a flexible API for customizing charts to fit your needs.

Create variety of charts in your next web applications with Chart.js and react which helps in data visualization in software development.


ReplayBird - Driving Revenue and Growth through Actionable Product Insights

ReplayBird is a digital experience analytics platform that offers a comprehensive real-time insights which goes beyond the limitations of traditional web analytics with features such as product analytics, session replay, error tracking, funnel, and path analysis.

With Replaybird, you can capture a complete picture of user behavior, understand their pain points, and improve the overall end-user experience. Session replay feature allows you to watch user sessions in real-time, so you can understand their actions, identify issues and quickly take corrective actions. Error tracking feature helps you identify and resolve javascript errors as they occur, minimizing the negative impact on user experience.

With product analytics feature, you can get deeper insights into how users are interacting with your product and identify opportunities to improve. Drive understanding, action, and trust, leading to improved customer experiences and driving business revenue growth.

Try ReplayBird 14-days free trial

Further Reading:

REST API Error Handling 101 and its Best Practices
REST API error handling is an essential part of any developer’s skill set. This article will provide an overview of REST API error handling 101 and its best practices.
Cohort Analysis - A Comprehensive Overview of its Benefits
Cohort Analysis helps identify patterns in user behavior by analyzing users over time. Get an overview of what Cohort Analysis is and how it can be used to gain valuable insights into user behavior.
Behavioral Analytics: A Complete Guide - 5 Behavioral Analytics Tools
Behavioral analytics provides insight into user’s actions, responses and decisions typically considering digital purchases.

Uma
Content writer at ReplyBird, I'm excited about understanding SEO from a distinct POV. I write about how brands can use user experience to improve and benefit businesses and SAAS.
Chennai

Try ReplayBird for free

Fast & visual way to understand your users. No credit card required.