{ sung.codes }

by dance2die
🌞
Blog
← Go Back

Displaying Multiple Google Charts in React (react-google-charts)

Broken Post?Let me know

I was working on displaying multiple GitHub traffic charts using a Google Chart NPM package for React, react-google-charts.

Problem

Out of many charts, only the first one chart is populated.

Question

How do we fix it?

TL;DR

Use a unique graph_id value.

Getting Started by Copying & Pasting

Here is the sample code in Quick Start section.

<div className={'my-pretty-chart-container'}>
<Chart
chartType="ScatterChart"
data={[['Age', 'Weight'], [8, 12], [4, 5.5]]}
options={{}}
graph_id="ScatterChart"
width="100%"
height="400px"
legend_toggle
/>
view raw ScatterChar.App.js hosted with ❤ by GitHub

In my case, I needed to display a line chart so updated chartType to LineChart.

<Chart
chartType="LineChart"
...
graph_id="LineChart"
...
/>
view raw LineChart.App.js hosted with ❤ by GitHub

So the code for displaying multiple charts is as follows.

const visitors = graphDetails
.map(visitor => {
...
return (
<Chart
chartType="LineChart"
...
graph_id="LineChart"
...
/>);
});
view raw fillcharts.js hosted with ❤ by GitHub

But for some reason, it was populating one graph.

chrome 2017 09 21 10 01 50 1

Resolution

After hours of researching and debugging, I found the problem.

Here you see that each chart had the same id="LineChart". chrome 2017 09 21 10 04 29

Each chart needs to have a unique ID. I chose an easy way out and used shortid NPM package.

import shortid from 'shortid';
...
const visitors = graphDetails
.map(visitor => {
const id = shortid.generate();
...
return (
<Chart
chartType="LineChart"
...
graph_id={id}
...
/>);
});

Conclusion

Each chart_id needs to be unique.

I hope you don't struggle to populate multiple Google Chart graphs.

You can find the commit detail on GitHub in my code.