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.
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:
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.
2. Creating a bar chart with Chart.js
Similarly, we can work with a Bar Chart in Chart.js. Here’s an example:
- 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:
- This code has a function called PieChart that makes pie charts with Chart.js and ReactJS.
- It uses two arrays: labels for the names of the slices and data for the values of the slices. It also has some options for the colors and borders of the slices.
- The function returns a PieChart component that uses props from data.
- To use this function in other files, export it as the default and import it with import {PieChart} from "react-chartjs-2".
- You can also import other chart types like import {BarChart} from "react-chartjs-2" or import {LineChart} from "react-chartjs-2".
- 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.
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:
- 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.
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.
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!