Unlocking Data Visualization with Google Charts and React
What is Google Charts?
Google Charts is a free, modern, and actively-maintained JavaScript charting service from Google that is efficient and easy to use in projects. It offers an extensive set of customization options and a rich chart gallery with many options to choose from. Google Charts is compatible with a wide range of devices, has cross-browser compatibility and cross-platform capabilities, and uses HTML and SVG, eliminating the need for additional plugins.
Setting up the Project
To use Google Charts in a React application, start by setting up a React app and installing the react-google-charts
package. This package is a modern, well-maintained, thin, typed, React wrapper for Google Charts that makes it easy for developers to use React with Google Charts.
npm install react-google-charts
Creating Your First Chart
To begin designing the interface, open the project in a text editor and remove all code inside the return method in the src/App.js
file. Next, create a new file called charts.js
in the src
directory and build your charts. Import react-google-charts
and get the Chart
property. Create a data variable to house the data to be displayed on the chart, and customize the chart as needed.
import { Chart } from 'react-google-charts';
const data = [
['Year', 'Sales'],
['2015', 100],
['2016', 200],
['2017', 300],
];
const options = {
title: 'Sales by Year',
hAxis: { title: 'Year' },
vAxis: { title: 'Sales' },
};
const ChartComponent = () => {
return (
);
};
Visualizing Your Chart
Run the server to preview the app, and see what you’ve built so far. The chart should be interactive and easy to generate with just a few lines of code.
Manipulating Your Chart using React Hooks
Use React Hooks to keep track of changes and pass data down as props to components. Create a data source, such as a JSON file, and use the useState
Hook to keep track of the data to be passed down to components. Create a button that fetches this data and updates the Hook.
import { useState, useEffect } from 'react';
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await fetch('data.json');
const jsonData = await response.json();
setData(jsonData);
};
fetchData();
}, []);
const handleClick = () => {
// Update the data here
setData([...data, { year: 2020, sales: 400 }]);
};
Using Multiple Charts
Update the App.js
file to include multiple charts, and pass the required data to each chart as props. Use a map function to loop through the data and show the resulting charts.
import React from 'react';
import ChartComponent from './ChartComponent';
const App = () => {
const data = [
{ year: 2015, sales: 100 },
{ year: 2016, sales: 200 },
{ year: 2017, sales: 300 },
];
return (
))}
);
};