In this tutorial, you will learn how to create a stacked bar chart using the Google Charts library to visualize data in a React JS application.
How to Implement Google Bar Charts in React Js Application
Steps to make stacked bar charts using google charts:
Step 1 – Create React App
Run the following command on your cmd to create a new react app:
npx create-react-app my-react-app
To run the React app:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install Bootstrap & react-google-charts
Run the following command to install react-bootstrap and Google Charts package into your react app:
npm install bootstrap # npm npm install react-google-charts # yarn yarn add react-google-charts
Step 3 – Create Stacked bar Charts Component
Navigate to the src directory of your React JS app, and create a Google Stacked Bar Chart component named GoogleBarChart.js
for the data visualized in it:
import React, { Component } from "react";
import Chart from "react-google-charts";
const data = [
['City', '2010 Population', '2000 Population'],
['New York City, NY', 8175000, 8008000],
['Los Angeles, CA', 3792000, 3694000],
['Chicago, IL', 2695000, 2896000],
['Houston, TX', 2099000, 1953000],
['Philadelphia, PA', 1526000, 1517000],
];
class GoogleBarChart extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="container mt-5">
<h2>React Basic Bar Chart with Multiple Series</h2>
<Chart
width={'700px'}
height={'320px'}
chartType="BarChart"
loader={<div>Loading Chart</div>}
data={data}
options={{
title: 'Population of Largest U.S. Cities',
chartArea: { width: '50%' },
hAxis: {
title: 'Total Population',
minValue: 0,
},
vAxis: {
title: 'City',
},
}}
rootProps={{ 'data-testid': '1' }}
/>
</div>
)
}
}
export default GoogleBarChart;
The render method of this class returns a container div element containing a heading and the Chart component. The Chart component is passed various props including the width and height of the chart, the type of chart to be rendered, the data to be displayed, and various options for customizing the chart’s appearance.
Finally, the GoogleBarChart class is exported as the default export of the module, which allows it to be imported and used in other files.
Step 4 – Import Component in App.js
In this step, you need to add GoogleBarChart.js file in src/App.js
file:
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import GoogleBarChart from './components/GoogleBarChart';
function App() {
return (
<div className="App">
<GoogleBarChart />
</div>
);
}
export default App;
Conclusion
That’s it, you have learned how to create react bar chart component in react js application using google charts library.