DEV Community

Cover image for How to use Google Charts with React for dynamic data visualization
Ably Blog for Ably

Posted on • Originally published at ably.com

How to use Google Charts with React for dynamic data visualization

This post was originally written by Tooba Jamal on the Ably Blog

According to research from Matillon and IDG, data volumes increase by 63 percent per month on average in an organization. Examining such substantial volumes of data without the right tools makes it impossible to make informed decisions, even in small businesses. The key to deriving useful and profit-driving insights from data is data visualization - which turns complex raw figures into meaningful visual representations of the data.

Google Charts is a free data visualization library provided by Google. Its straightforward API, diverse chart options, customization capabilities and interactivity make it a powerful tool for presenting data in a user-friendly format.

Due to its popularity, the React community has developed a “react-google-charts” library to streamline the integration of Google Charts into React applications. The React chart library offers a user-friendly experience and yields more robust results compared to other data visualization libraries available for React. It also offers the ability to achieve different chart types in just a single component by passing appropriate props as we’ll see later in the article.

With an understanding of how to use Google Charts with React in hand, you could take on projects such as a no-code data analysis website, a company dashboard, or an expense tracker - just to give a few examples. So, let’s look at how to get started using Google Charts with React!

Getting started with Google Charts in React

The react-google-charts library accepts data in a variety of formats from a range of sources, including arrays, JSON, Google Sheets, and external APIs. The charts it generates come with default interactivity and responsiveness and allow for dynamic realtime updates.

Setting up a basic React project using Vite

Vite is a recommended bundler for React; thus, we'll use Vite in this tutorial. You can also use other tools like Create React App (CRA) instead.

Since this tutorial focuses on using React Google Charts, we are using Tailwind CSS for styling so we keep our focus on React. If you're unfamiliar with Tailwind, you don't need to be concerned as we'll walk through the purpose of the classes we apply to our elements for styling throughout the tutorial.

The full project code is available on Github here, so don’t hesitate to install the project on your local machine and play around with it.

Begin by running the following command in your terminal window npm create vite@latest project-name. This will prompt you to answer a few questions related to the framework and variant. We will select React and JavaScript.

npm create vite@latest google-charts-in-react
Select a framework: React
Select a variant: JavaScript
Enter fullscreen mode Exit fullscreen mode

Installing and importing Google Charts using react-google-charts

Next, navigate to your new project directory and run the following command to install react-google-charts in your project: npm install react-google-charts.

Now, you're ready to run the project and use the library to visualize some data.

To start visualizing your data, import the library in your App.jsx file.

// App.jsx

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

function App() {

}
Enter fullscreen mode Exit fullscreen mode

Creating your first chart with Google Charts and React
Google Charts offers a wide range of charts to cater to various needs, including advanced visualizations. A few of the most common charts are:

  • Line chart: Suitable for visualizing time series data.
  • Bar chart: Useful for comparing data across categories.
  • Scatter chart: Helpful for visualizing patterns in data.
  • Pie chart: Suitable for representing data as a percentage.
  • Histogram: Useful for visualizing data distribution.

Let’s create a small amount of dummy data to begin visualising it. Within the temperatureData array below, the first array represents the headers or labels that we'll use to label the chart's axes, while the subsequent arrays contain our actual data values.

const temperatureData = [
  ['Year', 'Highest Temperature'],
  [2017, 32],
  [2018, 35],
  [2019, 31],
  [2020, 37],
  [2021, 30]];
Enter fullscreen mode Exit fullscreen mode

In this data, we're depicting the highest temperatures recorded over the last five years. Since a line chart is well suited for displaying time series data, we'll use it to display this information in the browser. This can be done in two easy steps:

1. First, add temperatureData to your App.jsx file

import { Chart } from react-google-charts;

function App() {
  const temperatureData = [
    ['Year', 'Highest Temperature'],
    [2017, 32],
    [2018, 35],
    [2019, 31],
    [2020, 37],
    [2021, 30]];

  return (
    <div></div>
  )}
Enter fullscreen mode Exit fullscreen mode

2. Next, pass the temperatureData as data prop into the component as shown in the code snippet below. Since we want to create a line chart, we set chartType prep equal to "LineChart".

<div className="py-10">
  <Chart chartType="lineChart" data={temperatureData} />
</div>
Enter fullscreen mode Exit fullscreen mode

The className of “py-10” is a Tailwind CSS utility class that adds a vertical padding of 2.5rem to an element.

Combining both of the steps, our App.jsx file looks like the code in the code below.

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

function App() {
    const temperatureData = [
        ['Year', 'Highest Temperature'],
        ['2018', 34],
        ['2019', 36],
        ['2020', 36],
        ['2021', 39],
        ['2022', 40]
    ];

    return (
        <div className='py-10'>
            <Chart
                chartType="LineChart"
                data={temperatureData}
            />
        </div>
    )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

As discussed above, the react-google-charts library has a straightforward API. It simply requires you to return a component with two essential props: chartType and data prop. The chartType specifies the type of chart you want to create, and data represents the data you intend to visualize.

Data format required by Google Charts

To ensure that the charts render as expected, it's crucial to format your data. When using Google Charts in React, your data should be organized in a tabular format, like a spreadsheet, with rows and columns. Where the first row represents a header while the subsequent rows represent the data values.

If you don't have data from an external source and need to represent it within your React application, you can structure it as an array of arrays. In this arrangement, the outer array represents a table, while the inner arrays represent individual rows and columns, as shown in the figure below.

Data format required by Google Charts

For instance, in the top example, we have the same temperature data used to create a line chart, with the first array representing axis labels and the subsequent arrays containing the data points. The second example demonstrates how student marks data can be structured in a similar way.

Customizing charts in Google Charts

React Google Charts offers extensive customization options to tailor your charts according to your design and display requirements. It gives you control to customize the chart title, axes, colors, design, and even animation. All it requires is passing your preferences as a prop in a component in object form.

const options = {
    title: 'Highest Temperature in last five years',
    backgroundColor: '#f7f7f7',
    hAxis: {
        title: 'Year',
    },
    vAxis: {
        title: 'Temperature °C',
    },
    colors: ['#007bff'],
    lineWidth: 2,
    pointSize: 6,
    animation: {
        startup: true,
        duration: 1000,
        easing: 'out',
    },
};
Enter fullscreen mode Exit fullscreen mode

In the code sample above, the options object defines our preferences for customizing the line chart we created. The object keys represent the following:

  • title: Represents the chart title; in our case, it's “Highest Temperature in the Last Five Years.”
  • backgroundColor: Specifies the background color we want for our chart.
  • hAxis: Refers to the horizontal axis (x-axis) of our chart.
  • vAxis: Represents the vertical axis (y-axis).
  • colors: Allows us to define the colors for our chart lines; multiple colors can be used for multi-line charts.
  • lineWidth: Sets the width of the chart lines.
  • pointSize: Determines the size of data points on the chart.
  • Animation: Provides the option to add animations to the chart display.

The charts are responsive by default, However, you can control their width and height by passing the “width” and “height” prop to the chart component. The props accept the height and width as a string like width={‘90%’}.

Dynamic data integration in React Google Charts

In the real world,we often encounter dynamic data that requires continuous analysis and its ongoing representation in our charts. To understand how we can handle dynamic data with react-google-charts, let's consider a scenario in which we need to analyze different categories of profit data.

The dataset consists of two columns: “category” and “profit”.Each row represents the profit a business makes in a specific category. Our goal is to dynamically update and visualize this data in a Google chart. We can achieve this in following steps:

1. Start by storing the initial data in a state variable.

const [data, setData] = useState([
    ['Category', 'Profit'],
    ['Household', 5000],
    ['Cosmetics', 3100],
    ['Clothing', 1500],
    ['Personal care', 1200],
    ['Auto parts', 4000],])
Enter fullscreen mode Exit fullscreen mode

2. Define a function “handleDataUpdate” that uses the .map() method to iterate over the data state. If the entry has an index equal to 0 (representing the headers array), it is returned as-is. For any other index, the function generates a random profit value within the range of 6000.

function handleDataUpdate() {
      const newData = data.map((entry, index) => {
        if (index === 0) {
          return entry;
        } else {
          const newProfit = generateRandomProfit();
          return [entry[0], newProfit];
        }
      });
      setData(newData);
    }
Enter fullscreen mode Exit fullscreen mode

3. The “generateRandomProfit” function is used to generate random profit in the “handleDataUpdate” function.

function generateRandomProfit() {
      return Math.floor(Math.random() * 5000) + 1000;
    }
Enter fullscreen mode Exit fullscreen mode

4. Attach the “handleDataUpdate” function to the “onClick” event of the “Update Data” button so that the data gets updated whenever a user clicks the button.

return (
    <div className='py-10 flex flex-col items-center justify-center'>
      <button
      className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800"
      onClick={handleDataUpdate}>
        Update Data
      </button>
      <Chart
        width={'70%'}
        chartType="BarChart"
        data={data}
        options={options}
        chartEvents={chartEvents}
      />
    </div>
  )
Enter fullscreen mode Exit fullscreen mode

Combining all of this, our code looks like the code in the code below.

function App() {
    const [data, setData] = useState([
        ['Category', 'Profit'],
        ['Household', 5000],
        ['Cosmetics', 3100],
        ['Clothing', 1500],
        ['Personal care', 1200],
        ['Auto parts', 4000]
    ]);

    function generateRandomProfit() {
        return Math.floor(Math.random() * 5000) + 1000;
    )

    function handleDataUpdate() {
        const newData = data.map((entry, index) => {
            if (index === 0) {
                return entry;
            } else {
                const newProfit = generateRandomProfit();
                return [entry[0], newProfit];
            }
        });
        setData(newData);
    }

    return  (
        <div className='py-10 flex flex-col items-center justify-center'>
            <button
            className='text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus: ring-blue-300 font-medium'
            onClick={handleDataUpdate}>
                Update Data
            </button>
            <Chart
                width={'70%'}
                chartType='BarChart'
                data={data}
            />
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

The classes added to the <div> element apply a vertical padding of 2.5rem, create a flex container with a column direction, and center its elements. The classes applied to the tag give our button a white color, blue background, and additional styling for hover and focus states.

The width prop just sets the width of the chart equal to 70% of its parent element.

Using APIs or live data sources with Google Charts in React

In many cases, when developing robust web experiences, we need to integrate live APIs or live data sources. Let's consider an example: building a dashboard that tracks user activities on a social media website. In this scenario, we require realtime data from our social media platform to provide realtime insights.

To efficiently manage realtime data and deliver a seamless web experience, Ably React Hooks offer a convenient solution. Ably React Hooks simplify working with realtime data, ensuring that everything stays up to date enabling developers to respond to changes without the complexities of configuring WebSockets. Read more about Ably React Hooks here.

Interactivity and event handling

Google Charts provide interactivity and the ability to attach events to visualizations to achieve specific results. By default, the charts include tooltips, which enhance user interaction, and attaching events is as simple as passing a “chartEvents” prop.

The “chartEvents” prop should be an array of objects, where each object includes an eventName and a callback function that defines the desired behavior for the event.

const chartEvents = [{
    eventName: 'select',
    callback({ chartWrapper }) {
        const selectedItems = chartWrapper.getChart().getSelection();
        if (selectedItems.length > 0) {
            const selectedItem = selectedItems[0];
            const row = selectedItem.row + 1;
            const dataPoint = data[row];
            alert(`You clicked on category ${dataPoint[0]} with profit ${dataPoint[1]}`);
        }
    }
}];
Enter fullscreen mode Exit fullscreen mode

In the above example, we're using the “select” event which is similar to the standard click event. When a user clicks on a point within a chart, they receive relevant information through an alert.

Here are some key concepts related to event handling:

  • chartWrapper:This is a reference to the container that holds our Google Chart.
  • getChart(): This function returns the underlying Google Chart associated with the wrapper.
  • getSelection(): This function returns the information about the selected chart elements or data points.

Since the first array in our data is for axes labels, we need to add 1 to the retrieved row index to get the correct results. “dataPoint” variable contains values for both “Name” and “Marks” columns that we use in the alert method to display the relevant information.

Customizing tooltips

While tooltips are displayed by default, you can customize the events that trigger the tooltips by modifying the options object. You can achieve this by adding a tooltip object to the options with a “trigger key” to control the behavior. You can choose one of the following values for the trigger property:

  • focus (Default): Tooltips are displayed when a user hovers over a chart element or data point.
  • none: No tooltips are shown.
  • selection: Tooltips are displayed when a user clicks on a chart element or data point.
const options = {
    title: 'Profit by Category',
    hAxis: {
        title: 'Category',
    },
    vAxis: {
        title: 'Profit',
    },
    tooltip: {
        trigger: 'none',
    },
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

As the demand for applications featuring data visualizations continues to grow, it's essential for developers to stay ahead of the trend. Fortunately, react-google-charts empowers developers with its straightforward API and rich customization options, making data visualization accessible to all.

While some advanced features of Google Charts, such as controls and data manipulation, were initially absent in react-google-charts, the library has evolved over time, now offering access to a wide range of features. This ongoing development ensures that developers can create even more sophisticated and feature-rich data visualizations.

Combining data visualization with React opens up endless possibilities, allowing developers to build data-rich applications without the need to expand their tech stack. As you explore these opportunities, remember that the world of data is at your fingertips, ready to be transformed into actionable insights and meaningful user experiences.

What’s next?

Now that you've gained insight into Google Charts in React, you are ready to develop data driven experiences in React. Take a closer look at advanced visualizations and customizations you can apply to your charts here, and unlock the full potential of your data.

Let us know what you are building and how you’re using data visualization to transform data into information by tweeting @ablyrealtime or dropping us a line in /r/ablyrealtime.

Top comments (0)