Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is React Chart.Js?
3.
Importance of React and Chart.js in Modern Web Development
4.
How to Install React Chart.Js?
4.1.
Setting up React Application
4.2.
Bar Chart
4.3.
Line Chart
4.4.
Pie Chart
5.
Components of React Chart Js
6.
Customization and Configuration:
6.1.
Colors and Styles:
6.2.
Legends and Tooltips:
6.3.
Scales and Axes:
7.
Interactive Features
7.1.
Hover Effects:
7.2.
Click Events:
8.
Advanced Topics in Reach ChartJS
8.1.
Handling Real-Time Data
8.2.
Server-Side Rendering
8.3.
Edge Cases
8.3.1.
Dealing with Large Datasets:
8.3.2.
Handling Missing or Incomplete Data:
9.
Advantages of React ChartJs
10.
Disadvantages of React ChartJs
11.
Comparisons with Other Libraries
11.1.
D3.js
11.2.
Highcharts
11.3.
Documentation
11.4.
Community Forums and Channels
12.
Future Trends
12.1.
Integration with Other Libraries
12.2.
Upcoming Features in Chart.js
13.
Frequently Asked Questions
13.1.
What is Chartjs? 
13.2.
Is React Chartjs 2 open-source? 
13.3.
What is chartjs used for? 
14.
Conclusion
Last Updated: Mar 27, 2024
Medium

Using Chart.js with React

Author Rinki Deka
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

React Chart.js simplifies chart and graph creation in React, offering a user-friendly JavaScript library. Ideal for displaying visual data on websites, it streamlines the process for easy chart implementation.

react chartjs

This amalgamation not only simplifies the process of rendering data in a graphical format but also opens up avenues for more interactive and visually appealing applications. Through the course of this article, we'll delve into the intricacies of setting up, rendering basic charts, and exploring the plethora of features offered by the synergy of React and Chart.js.

What is React Chart.Js?

React Chart.js is a React wrapper for the Chart.js library, a popular JavaScript library for creating interactive and customizable charts and graphs. React Chart.js simplifies the integration of Chart.js into React applications by providing React components that encapsulate the Chart.js functionality. It allows developers to easily incorporate various types of charts, such as line charts, bar charts, pie charts, and more, into their React-based web applications. This integration enables the creation of dynamic and visually appealing data visualizations within the React framework.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Importance of React and Chart.js in Modern Web Development

React, a JavaScript library for building user interfaces, and Chart.js, a simple yet flexible JavaScript charting library, are integral in modern web development for creating interactive and visually compelling applications. Together, they empower developers to build intuitive data visualization interfaces that enhance user engagement and provide insightful data analytics.

How to Install React Chart.Js?

Setting up React Application

First, make sure you have Node.js installed on your machine. If not, download it from the official Node.js website.

Create a new React app by opening a terminal and running the following command:

npx create-react-app react-chartjs-app
cd react-chartjs-app

Installing Chart.js and react-chartjs-2

In the project directory, install chart.js and react-chartjs-2 using npm:

npm install chart.js react-chartjs-2

Rendering Basic Charts

Bar Chart

Code Example

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


const data = {
  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  datasets: [{
    label: '# of Votes',
    data: [12, 19, 3, 5, 2, 3],
    backgroundColor: [
      'rgba(255, 99, 132, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(255, 206, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(255, 159, 64, 0.2)'
    ],
    borderColor: [
      'rgba(255, 99, 132, 1)',
      'rgba(54, 162, 235, 1)',
      'rgba(255, 206, 86, 1)',
      'rgba(75, 192, 192, 1)',
      'rgba(153, 102, 255, 1)',
      'rgba(255, 159, 64, 1)'
    ],
    borderWidth: 1
  }]
};


const BarChart = () => (
  <Bar data={data} />
);

export default BarChart;

 

Output

output

Explanation

In this code snippet, we import Bar from react-chartjs-2 and create a BarChart component. We define our data and options, specifying labels, dataset properties, and rendering the bar chart using the Bar component.

Line Chart

Code Example

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


const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June'],
  datasets: [{
    label: 'Sales',
    data: [3, 2, 2, 1, 5, 3],
    fill: false,
    backgroundColor: 'rgb(75, 192, 192)',
    borderColor: 'rgba(75, 192, 192, 0.2)',
  }]
};


const LineChart = () => (
  <Line data={data} />
);


export default LineChart;

Output

output

Explanation

Here, we create a line chart to depict sales over six months. We import Line from react-chartjs-2, define our data, and render the line chart using the Line component.

Pie Chart

Code Example

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


const data = {
  labels: ['Red', 'Blue', 'Yellow'],
  datasets: [{
    data: [300, 50, 100],
    backgroundColor: [
      '#FF6384',
      '#36A2EB',
      '#FFCE56'
    ],
    hoverBackgroundColor: [
      '#FF6384',
      '#36A2EB',
      '#FFCE56'
    ]
  }]
};


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


export default PieChart;

 

Output

output

Explanation

In this snippet, we create a simple pie chart with three data points. We import Pie from react-chartjs-2, define our data with labels, dataset values, and colors, then render the pie chart using the Pie component.

Components of React Chart Js

React Chart.js is typically organized into components that correspond to different types of charts and provide a way to customize and render those charts within a React application. The core components often include:

  • Bar Component: Represents a bar chart. It allows customization of data, labels, and styling for bar-based visualizations.
  • Line Component: Represents a line chart. It enables the rendering of data as a line, supporting features like point markers and smooth curves.
  • Doughnut Component: Represents a doughnut chart. It allows the creation of circular charts with a hole in the center, suitable for displaying data proportions.
  • Pie Component: Represents a pie chart. Similar to the doughnut chart, it displays data in a circular format, with slices representing data proportions.
  • Radar Component: Represents a radar chart. It is useful for displaying multivariate data in a radial format, showcasing data points on different axes.
  • PolarArea Component: Represents a polar area chart. It displays data in a circular format with each segment representing a data point.
  • Bubble Component: Represents a bubble chart. It displays data points using circles, where the size of the circle represents an additional data dimension.
  • Scatter Component: Represents a scatter plot. It displays individual data points without connecting lines, useful for visualizing the distribution of data.

Customization and Configuration:

Colors and Styles:

Customizing the aesthetics of your charts is a fundamental aspect of data visualization as it enhances readability and user engagement. React and Chart.js provide a myriad of options for altering colors and styles to suit your application's theme.

Code Example:

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


const data = {
  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  datasets: [
    {
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }
  ]
};


function ColorfulBarChart() {
  return (
    <Bar data={data} />
  );
}


export default ColorfulBarChart;

Explanation:

In this example, we define an array of background colors and border colors for each bar in our chart. These colors are applied in the order they appear in the array, corresponding to the order of bars. The backgroundColor and borderColor properties accept rgba values, which allow you to specify the color and opacity.

Legends and Tooltips:

Legends help in identifying what each plot on your chart represents, while tooltips provide additional information when a user hovers over a data point.

Code Example:

const options = {
  plugins: {
    legend: {
      display: true,
      labels: {
        color: 'rgb(255, 99, 132)'
      }
    },
    tooltip: {
      enabled: true
    }
  }
};


function InteractiveBarChart() {
  return (
    <Bar data={data} options={options} />
  );
}
export default InteractiveBarChart;

Explanation:

We enable the display of legends and tooltips through the options object. The legend and tooltip properties under plugins are used to control the appearance and behavior of legends and tooltips respectively.

Scales and Axes:

The scales and axes provide a reference frame to understand the data points on your chart, allowing for better interpretation of data.

Code Example:

const options = {
  scales: {
    y: {
      beginAtZero: true
    }
  }
};


function ScaledBarChart() {
  return (
    <Bar data={data} options={options} />
  );
}


export default ScaledBarChart;

Explanation:

In this example, we customize the y-axis to start at zero by setting the beginAtZero property to true under scales in the options object. This ensures that the y-axis starts at a baseline of zero, providing a clearer perspective on the data values.

Interactive Features

Hover Effects:

Adding hover effects not only makes your charts interactive but also enhances user engagement by providing additional information or visual feedback on mouse over.

Code Example:

const options = {
  plugins: {
    tooltip: {
      enabled: true
    }
  }
};


function HoverableBarChart() {
  return (
    <Bar data={data} options={options} />
  );
}


export default HoverableBarChart;

Explanation:

Here, we enable tooltips in the chart configuration through the options object. Now, whenever a user hovers over a data point, a tooltip displaying the value of that point will appear.

Click Events:

React and Chart.js enable the capturing of click events on charts which can be used to create interactive dashboards or drill-down charts.

Code Example:

function handleClick(event, elems) {
  if(elems.length > 0){
    const index = elems[0].index;
    alert(`You clicked on ${data.labels[index]}`);
  }
}


function ClickableBarChart() {
  return (
    <Bar data={data} onElementClick={handleClick} />
  );
}
export default ClickableBarChart;

Explanation:

In this snippet, we define a handleClick function that gets triggered upon clicking on an element in the chart. We then pass this function to the onElementClick prop of the Bar component.

Advanced Topics in Reach ChartJS

Handling Real-Time Data

Real-time data handling is vital for applications requiring continuous data updates like stock market dashboards.

Code Example:

import React, { useState, useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import socketIOClient from "socket.io-client";

const socket = socketIOClient('http://127.0.0.1:4001');


function RealTimeChart() {
  const [data, setData] = useState({ labels: [], datasets: [] });


  useEffect(() => {
    socket.on('data', newData => {
      setData(prevData => ({
        ...prevData,
        labels: [...prevData.labels, newData.label],
        datasets: [{
          ...prevData.datasets[0],
          data: [...prevData.datasets[0].data, newData.value]
        }]
      }));
    });
    return () => socket.disconnect();
  }, []);

  return (
    <Line data={data} />
  );
}

export default RealTimeChart;

 

Explanation:

In this example, we utilize a WebSocket connection through Socket.io to receive real-time data updates which are then appended to our chart data using the setData function.

Server-Side Rendering

Server-side rendering (SSR) with React and Chart.js can improve the initial load time of your application.

Code Example:

// server.js

import { renderToString } from 'react-dom/server';
import App from './App';

app.get('*', (req, res) => {
  const content = renderToString(<App />);
  res.send(content);
});

 

// App.js

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

function App() {
  return (
    <Bar data={data} />
  );
}

export default App;

 

Explanation:

Here, we demonstrate a simplified setup for server-side rendering. In server.js, we utilize renderToString to render our App component to a string, which is then sent as the response to the client. The App component contains our Bar chart from react-chartjs-2.

Edge Cases

Dealing with Large Datasets:

Handling large datasets efficiently is crucial to ensure the performance and responsiveness of your charts.

Code Example:

const data = {
  labels: Array.from({length: 1000}, (_, i) => i + 1),
  datasets: [{
    data: Array.from({length: 1000}, () => Math.random() * 100)
  }]
};

function LargeDatasetChart() {
  return (
    <Line data={data} options={{ animation: false }} />
  );
}
export default LargeDatasetChart;

 

Explanation:

In this example, we're creating a dataset with 1000 data points. To enhance performance, we disable animations by setting the animation option to false, which can significantly improve rendering time for large datasets.

Handling Missing or Incomplete Data:

Incomplete or missing data can distort the visual representation of the chart. It's essential to handle such cases gracefully.

Code Example:

const data = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
  datasets: [{
    data: [10, null, 20, null, 30]
  }]
};

function MissingDataChart() {
  return (
    <Line data={data} options={{ spanGaps: true }} />
  );
}
export default MissingDataChart;

 

Explanation:

In this code snippet, we have missing data for February and April. By setting the spanGaps option to true, Chart.js will interpolate the missing values and draw a line spanning the gaps.

Advantages of React ChartJs

  • Ease of Use: React and Chart.js are easy to set up and use, making it simple for developers to create interactive charts with a small amount of code.
  • Customizability: Both libraries provide extensive customization options allowing developers to create visually appealing charts that match the application's design requirements.
  • Performance: React's virtual DOM and Chart.js's efficient rendering make it a performant choice for rendering charts in web applications.

Disadvantages of React ChartJs

While React and Chart.js cover a wide range of charting needs, they might fall short for specialized or highly customized charting requirements. Developers may need to look into other libraries or solutions for such cases.

Comparisons with Other Libraries

D3.js

D3.js provides lower-level control over the rendering and animation of data visualizations, allowing for more complex and customized charts.

Compared to Chart.js, D3.js has a steeper learning curve and requires more code for the same visualizations.

Highcharts

Highcharts offers a wide variety of built-in chart types and is known for its ease of use.

Unlike Chart.js which is open-source, Highcharts requires a commercial license for commercial use.

Code Example for D3.js:

// D3.js example of creating a bar chart

const svg = d3.select('svg');
const data = [4, 8, 15, 16, 23, 42];
const x = d3.scaleLinear()
  .domain([0, d3.max(data)])
  .range([0, 420]);
svg.selectAll('rect')
  .data(data)
  .enter().append('rect')
  .attr('width', x)
  .attr('height', 20)
  .attr('y', (d, i) => i * 21);

Documentation

Comprehensive documentation is available for both React and Chart.js, covering a wide range of topics and examples to help developers get started.

Community Forums and Channels

Community support through forums like Stack Overflow, GitHub, and Discord channels provides a platform for developers to seek help and discuss best practices.

Future Trends

Integration with Other Libraries

The community is working towards better integration with other popular libraries and frameworks, making it even more versatile.

Upcoming Features in Chart.js

Upcoming releases of Chart.js are expected to include more built-in chart types, improved performance, and better real-time data handling capabilities.

Frequently Asked Questions

What is Chartjs? 

Chart.js, a simple yet flexible JavaScript charting library, are integral in modern web development for creating interactive and visually compelling applications.

Is React Chartjs 2 open-source? 

Chartjs is an open source library of Javascript which is mainly used for data visualization. It also supports various chart types like radar, bar, bubble, pie, area, line, scatter, and polar

What is chartjs used for? 

Chart.js offers a variety of customizable chart types for a diverse range of data visualization needs. It offers various types of data types as well. 

Conclusion

This article delved into the combined power of React and Chart.js for creating interactive, efficient, and visually appealing data visualizations. Through examples and comparisons, we explored the capabilities, advantages, and how to handle common challenges while working with these libraries. The support from the community and the continuous improvement through upcoming features makes React and Chart.js a compelling choice for developers looking to present data in an engaging manner.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
React Components Lifecycle
Next article
React Toastify
Live masterclass