The modern website application development process has now become more user-centric. Thus, application developers always focus on bringing responsive layouts and designs for users to keep them hooked with effective data visualization. In this regard, charts have become a viable tool for spreading information while engaging the audience with the website. In the website development space, Chart.js has now become a prominent giant in this regard. Web developers are coupling both Chart.js with React to harness the benefits of these unparalleled tools in the development process. In this article, we have come up with easy steps to get started with creating interactive graphs using Chart.js and React for beginners, their benefits, and more.
Meta-maintained React, which was founded by a software engineer, Jordan Walke in 2011 is an open-source JS library used to create responsive UIs for web, desktop, and mobile applications. The UIs are built by deploying components, fixing bugs, and abstracting rendering.
Contrarily, as the name implies, Chart.js is an open-source JS library specifically leveraged to develop interactive charts. In Layman’s terms, it is a charting library used to create various chart types such as pie, bar, line, scatter, and more.
Thus, the amalgamation of React and Chart.js helps developers create interactive charts for website, desktop, and mobile applications to enhance the overall user experience.
Let us start our journey from scratch for the deployment of React and Chart.JS for your next React Project! You will need Typescript and Vite for a hassle-free setup.
You can quickly bootstrap a new React application using Vite. Open your terminal and run the following commands:
npm create vite@latest
cd your-project-name
npm install
After the setup is complete, open your project in VS Code or any preferred IDE.
To use Chart.js in your React application, you will need to install both the library and its React wrapper:
npm install chart .js react-chartjs-2
If you are using Typescript, install the type definitions as well:
npm install @types/chart.js @types/react-chartjs-2
For better maintainability and clarity, organize your project with the following react project structure:
src
├── App.tsx
├── Main.tsx
├── components
│ ├── BarChart.tsx
│ └── PieChart.tsx
└── data
├── barChartData.ts
└── pieChartData.ts
This structure separates your components in components folder and data files, making it easy to manage and scale your project.
After the environment has been set up, you can now begin with creating your first chart. However, knowing some of the terms before we start creating the code is important. You can create different types of charts, including a line chart, using Chart.js in React.
Data object: This is the main element of the chart and in chart.js, data is passed as a prop to the React chart component, analyzing what will be displayed. You can consider this example to structure your data:
export const data = {
labels: ["Q1", "Q2", "Q3", "Q4"], // X-axis labels
datasets: [ // Y-axis data
{
label: "North America",
data: [50000, 70000, 80000, 65000], // Values for each quarter
backgroundColor: "rgba(75, 192, 192, 0.6)", // Color of the bars
borderColor: "rgba(75, 192, 192, 1)", // Border color of the bars
borderWidth: 1, // Width of the borders
},
],
};
Labels: Labels are usually text boxes located along a point on a chart, which depict the information contained in each point.
Datasets: This feature resembles all the data points plotted on the Y-axis (vertical). It consists of two more elements:
Label: It is the name associated with the dataset, which appears in tooltips and legends.
Data: It depicts the actual values that correspond to each label on the X-axis.
Options Object: As the name suggests, options objects refer to the optional customization options that help tailor the behavior and appearance of the chart. These options help improve the visualization of data by making it easy to interpret and engaging.
Example of How to Use Options and Data:
For instance, if you want to create a simple bar chart depicting sales data in North America over four quarters, you can use the 'data' structure above and define some options for further customization. The example below shows you how to set up your options:
const options = {
responsive: true,
};
Bar graphs are among the most widely used data visualization tools, which are ideal for analyzing trends over time or making comparisons. We will deep dive into how to create bar graphs using Chart.js in a React application.
A bar graph uses vertical or horizontal bars to represent data visually. It is often used for:
Category Comparisons: For example, revenue by region.
Trend Analysis: For example, quarterly sales performance.
If your business is looking to track quarterly revenue from regions like Europe, North America, Asia, and Australia, a bar graph will help you visualize and compare them effectively.
The first step is to create and organize your first dataset. Here is an example of quarterly revenue data structured in a separate file (note: it is static data and not dynamic data):
When the data is ready, you need to create React elements. To render the chart, refer to the following code.
import React from "react";
import { Bar } from "react-chartjs-2"; // import barchart component
import { Chart as ChartJS, CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend, ChartOptions } from "chart.js";
import { barChartDataRegions } from "../data/barChartData";
// Register Chart.js components
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);
function BarChart() {
const barChartOptions: ChartOptions<"bar"> = {
responsive: true,
plugins: {
legend: {
position: "top",
labels: { font: { size: 14 } },
},
title: {
display: true,
text: "Quarterly Revenue by Region",
font: { size: 16, weight: "bold" },
},
},
scales: {
y: {
beginAtZero: true,
title: { display: true, text: "Revenue ($)", font: { size: 14 } },
ticks: { callback: (value) => `$${value}`, font: { size: 12 } },
},
x: {
title: { display: true, text: "Quarter", font: { size: 14 } },
ticks: { font: { size: 12 } },
},
},
};
return (
<div style={{ margin: 20, padding: 20 }}>
<Bar options={barChartOptions} data={barChartDataRegions} />
</div>
);
}
export default BarChart;
Responsive Design: It makes the adjustment of the chart to any screen size.
Legend: It depicts data pertaining to datasets that are on the chart.
Title: As the name implies, the title provides a descriptive heading to the chart.
X-Axis: It is labeled as “Quarter.”
Y-Axis: It is labeled as “Revenue ($)” and begins at 0.
The <Bar> chart elements from react-chartjs-2 take the data and options as props, rendering the interactive chart.
Your chart will now display quarterly revenue and data points for North America, Europe, Asia, and Australia in a visually appealing and responsive format.
With this setup, you can quickly adapt your data or chart options to create even more advanced visualizations! Similarly, you can also make line charts or line graphs. Ideally, you need to fetch data from back-end servers API and convert large datasets or datasets array into the format that is needed by chart.js .
Pie charts are a powerful way to visualize proportions, helping audiences understand how different categories contribute to a whole. They are ideal for visualizing percentages or proportions in your data. This guide will give you a walkthrough on how to build a pie chart in React using the popular Chart.js library.
Pie charts are essential tools for showing the time allocated to each task. This helps in simplifying part-to-whole relationships and making comparisons by analyzing which is the biggest slice of the cake. These charts are useful in displaying time distribution across tasks, visualizing budget allocation across categories, and comparing contributions.
If you want to analyze weekly time spent on social media platforms such as YouTube, Twitter, and Instagram, a pie chart can help know the proportional time spent on each platform.
Organize and label your data to represent categories (e.g., social media platforms) and their respective values. Below is an example dataset for weekly hours spent on platforms:
Once the data is ready, create a reusable component to render the pie chart and final code.
import React from "react";
import { Pie } from "react-chartjs-2"; // import piechart component
import {
Chart as ChartJS,
ArcElement,
Title,
Tooltip,
Legend,
ChartOptions,
} from "chart.js";
import { pieChartData } from "../data/pieChartData";
// Register necessary components for Chart.js
ChartJS.register(ArcElement, Title, Tooltip, Legend);
const pieChartOptions: ChartOptions<"pie"> = {
responsive: true,
plugins: {
legend: {
position: "right",
labels: {
font: {
size: 14,
},
},
},
title: {
display: true,
text: "Time Spent on Social Media Platforms (Weekly)",
font: {
size: 18,
weight: "bold",
},
},
},
};
function PieChart() {
return (
<div style={{ width: "600px", margin: "20px auto" }}>
<Pie data={pieChartData} options={pieChartOptions} />
</div>
);
}
export default PieChart;
Final Output
There are ample charting libraries for React projects to choose from, each offering various chart types for visualizing data. Some of them include BizCharts, Echarts, Rumble Charts, Ant Design Charts, and more. You can choose them per the requirements of your business by considering the cost, features, development time, functionalities, and other parameters. Moreover, Chart.js offers a host of customization options that you can leverage to cater to your requirements.
In a nutshell, it can be inferred that Chart.JS can enhance data visualization in React apps. The in-built components of Chart.JS can be leveraged as per the customized requirements of your next React project. If you are thinking of building a user-friendly React app and outsourcing seasoned developers, worry not. At Angular Minds, the prowess of industry professionals with proven experience in end-to-end React app development will give skyrocketing success to your next React project. Inquire now to know the complete suite of services.
This website uses cookies to analyze website traffic and optimize your website experience. By continuing, you agree to our use of cookies as described in our Privacy Policy.