Learn More

Try out the world’s first micro-repo!

Learn More

Visualizing Data with React Google Charts

Visualizing Data with React Google Charts

Charts are more helpful for a better understanding of data than just looking at the numbers. In web apps, they’re useful in creating dashboards for visualizing site activities.

In this tutorial, we'll learn how to visualize data with React Google Charts. React Google Charts is a thin, typed, React wrapper with a free charting service and a JavaScript library by Google.

Built and maintained by Google, Google Charts is a free, easy-to-use interactive web service used to create graphical charts. Google Charts has a ton of customization options, ranging from a simple line graph to a more complex map tree. These charts are created from data input by the user. In response to the request, chart images are returned from the service.

Why Google Charts?

Google Charts are highly customizable and easy to use, making them a top choice when choosing among charts. Unlike other libraries, they’re also compatible on all platforms, ranging from mobile to desktop. They use HTML and SVG at their core, and therefore don’t depend on any additional library or plugin.

Setting Up a Project

We’ll start by setting up our React project. First, run the command below in your terminal:

npx create-react-app react-chart-app

Once the command above is done downloading the required libraries for the React app, navigate to the project directory using the command below:

cd react-chart-app

Installing React Google Chart

Install the react-google-chart plugin using the command below:

npm install --save react-google-charts

Building Components

To begin, let’s build our first components. First, create a file called Chart.jsx in the src/ folder:

Paste the code below:

import { Chart } from "react-google-charts";

export const data = [
[
"Courses",
"Mathematics",
"English",
"Chemistry",
"Physics",
"Biology",
"Average"
],
["Sam", 18, 10, 12, 16, 5, 12.2],
["Jessica", 13, 11, 5, 18, 2, 9.8],
["Suka", 15, 11, 7, 18, 9, 10],
["Isaac", 19, 11, 6, 8, 5, 9.8],
["Dee", 12, 11, 9, 16, 6, 10.8]
];

export const options = {
"title": "Test score in a classroom between 5 students",
"vAxis": { "title": "Grade" },
"hAxis": { "title": "Students" },
"seriesType": "bars",
"series": { "5": { "type": "line" } }
};

function Charts() {
return (
<Chart
chartType="ComboChart"
data={data}
options={options}
width={"100%"}
height={"400px"}
/>
);
}

export default Charts;

With the code block above, we imported the Chart components from the react-google-charts plugin installed earlier. The Chart component contains some props to enable graphical representation like the chartType prop, which gives us the ability to change the chart display type. The data prop accepts our input data, and the options prop accepts a map of options that contains the title, color, backgroundcolor, etc.

Updating App.js

Let’s clean up our App.js by replacing it with the code block below:

import './App.css';
import Charts from "./Charts";

function App() {
return (
<div className="App">
<Charts />
</div>
);
}
export default App;

The code block above simply imports and renders our Charts components.

To see what we’ve built so far, run the code on your browser using the command below:

npm start

Here, we have a chart showing the test scores of five students in a classroom.

Populating Charts with React Hooks

Before diving into working with React Hooks, let’s first get a grip of what hooks are.

React Hooks are state managers introduced in React 16.8. They allow us to use features like useState() and more without having to write a class.

We’ll be simulating responses from an external source or API, and then using React Hooks to manage the states and keep track of the data.

Working with JSON

First, create a data.json file in the src/ folder:

Next, paste the json code below into the newly created file:

{
"charts": [
{
"name": "Combo Chart",
"chartType": "ComboChart",
"data": [
[
"Courses",
"Mathematics",
"English",
"Chemistry",
"Physics",
"Biology",
"Average"
],
["Sam", 18, 10, 12, 16, 5, 12.2],
["Jessica", 13, 11, 5, 18, 2, 9.8],
["Suka", 15, 11, 7, 18, 9, 10],
["Isaac", 19, 11, 6, 8, 5, 9.8],
["Dee", 12, 11, 9, 16, 6, 10.8]
],
"options": {
"title": "Test score in a classroom between 5 students",
"vAxis": { "title": "Grade" },
"hAxis": { "title": "Students" },
"seriesType": "bars",
"series": { "5": { "type": "line" } }
}
},
{
"name": "Pie",
"chartType": "PieChart",
"data": [
["Task", "Hours per Day"],
["Code", 11],
["Eat", 5],
["Tweet", 2],
["Watch TV", 3],
["Sleep", 4]
],
"options": {
"title": "Pie Chart displaying daily activities",
"is3D": true
}
},
{
"name": "Scatter Chart",
"chartType": "ScatterChart",
"data": [
["Task", "Hours per Day"],
["Code", 7],
["Write", 11],
["Sleep", 2],
["Read", 5],
["Watch TV", 2]
],
"options": {
"title": "Scattered Chart displaying daily task"
}
}
]
}

The code above is in JSON format and will serve as our API response.

Creating States

We’ll be managing two states: the loading state (when the data is coming from the API) and the data state (when displaying the data in our chart). Paste the code block below into the App.js file:

import React, { useState, useEffect } from 'react';

function App() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(false);

useEffect(() => {

}, []);

.....
}

In the code block above, we imported the useState and useEffect components from the React library and then created two states: one for our loading gif, and the other to display the response data with useState.

Manipulating Our State

Now, let’s manage our state by updating the code in the App() function with the code block below:

import "./App.css";
import response from "./data.json";
import Charts from "./Charts";
import { useState, useEffect } from "react";

function App() {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(false);

useEffect(() => {
const id = setInterval(() => {
setLoading(false);
setData(response);
}, 3000);
return () => {
clearInterval(id);
};
}, [loading]);

.....
}

With the code block above, we import the data.json as a response that is passed into a timer function. This creates a delay of 3 seconds to simulate a fetch request, after which we set our loading to false (stop the spinner), and set the data to the response data.

Using Multiple Charts

The React Google Chart has a variety of chart types at our disposal.

In this section, we’ll be implementing a few of the charts to visualize our data coming from the data.json file.

When loading, we want to display a loading gif. Import the loading gif into the App.js file:

import spinner from "./spinner.gif";

Now, let's populate our app with other chart types. Next, update the return block by copying and pasting the code block below:

function App() {
.....

return (
<div className="App">
{loading ? (
<img src={spinner} alt="Loading" height={400} width={400} />
) : (
data.charts.map((i, index) => <Charts response={i} key={index} />)
)}
</div>
);
}

We’re looping through the response stored in the data hook and passing it to our Charts components as props while listening to the loading state. While the data is loading, the loading gif is displayed, and after 3 seconds, the data is displayed.

Updating the Charts Component

In the previous section, we successfully mapped and passed our response as props into the Charts component. Let’s update our Charts component to receive the props and render the charts. To achieve this, update the code in src/Charts.jsx file:

import { Chart } from "react-google-charts";

function Charts({ response }) {
const { data, options, chartType } = response;
return (
<Chart
chartType={chartType}
data={data}
options={options}
width={"100%"}
height={"400px"}
/>
);
}

export default Charts;

In the code block above, we are destructuring data, options, and chartType from the response prop, and then assigning their corresponding property to the Chart component.

We’ve successfully built our charts application! Let’s refresh our application to see the charts as shown below:

Use Cases for Data Visualization

Keeping track of user data and activities can be rigorous for users, admins, and developers since data is often presented in several rows and columns, making reading and interpreting it a strenuous task for the analyst. With visual data, anyone can easily understand the flow of data, thus making it easy for the brain to capture and process.

Examples of where visual charts are most often used:

  • Admin dashboards
  • Network mapping
  • Real-time data flow in stock markets

Conclusion

In this tutorial, we’ve explored the react-google-chart plugin, its uses, and how to use it to create dynamic charts for our applications. We also broadened our expertise by looking at other techniques for building complicated applications with React Hooks and the react-google-charts package.

Here is a link to the React Google Chart documentation for more implementation information.

Here is a link to the complete source code for this article.

Interested in becoming a Pieces Content Partner?

Learn More

Get our latest blog posts and product updates by signing up for our monthly newsletter! 

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Table of Contents

React

Data

More from Pieces