React Typescript Javascript Web

Embedding Google Trends with React

Blog post featured image

In the digital age, understanding and visualizing search trends can provide valuable insights into public interest over time. Google Trends is a widely used tool for this purpose, offering a glimpse into the relative search volume of keywords across various regions and languages.

There is one problem: Google Trends doesn’t have an API, and unofficial APIs barely works.

Google Trends offers the possibility to embed it, providing a <script> snippet, but if you tried to use that snippet you will quickly find out that there are issues when used in React.

So, in this blog post, we’ll guide you through the process of building a Google Trends Widget using React using Typescript.

Set Up Your React Project

If you haven’t already, create a new React project by running:

npx create-react-app google-trends-widget
cd google-trends-widget
npm start

This command sets up a new React application and starts a development server.

Create a new file named GoogleTrendsWidget.tsx in your project’s src directory. This component will be responsible for loading the Google Trends data and displaying it within your application.

import React, { memo, useEffect, useRef, useState } from "react";

interface GoogleTrendsWidgetProps {
  keyword: string;
  geo: string;
  startTime: string;
  endTime: string;
  type: "TIMESERIES" | "GEO_MAP" | "RELATED_QUERIES" | "RELATED_TOPICS";
}

const GoogleTrendsWidget: React.FC<GoogleTrendsWidgetProps> = memo(
  ({ keyword, geo, startTime, endTime, type = "TIMESERIES" }) => {
    const widgetRef = useRef<HTMLDivElement>(null);
    const [scriptLoaded, setScriptLoaded] = useState(false);

    // TODO: Load embed_loader.js script

    // TODO: Call the script in order to render Google Trends

    return scriptLoaded && <div ref={widgetRef} style={{ width: "100%" }} />;
  },
);

export default GoogleTrendsWidget;

GoogleTrendsWidget accepts several props:

  • keyword: The search term you want to track.
  • geo: The geographical location for the trend data (e.g., “US” for the United States).
  • startTime: The start date for the trend data in YYYY-MM-DD format.
  • endTime: The end date for the trend data in YYYY-MM-DD format.

First, we need to complete the component by loading the Google Trends embed script dynamically. We use a React useEffect hook to append the script to the document. Once the script is loaded, we update the state to indicate the script is ready.

useEffect(() => {
  if (scriptLoaded) {
    return;
  }
  const script = document.createElement("script");
  script.src =
    "https://ssl.gstatic.com/trends_nrtr/3620_RC01/embed_loader.js";
  script.addEventListener("load", () => setScriptLoaded(true));
  document.body.appendChild(script);
}, []);

Rendering the Widget

After the script is loaded, we use another useEffect hook to render the Google Trends widget. We check if all necessary props are provided and if the script is loaded. Then, we call renderExploreWidgetTo to render the widget into our component.

useEffect(() => {
  // Delete content if this is a redraw
  widgetRef.current.innerHTML = ""; 

  window.trends.embed.renderExploreWidgetTo(
    widgetRef.current,
    type,
    {
      comparisonItem: [{ keyword, geo, time: `${startTime} ${endTime}` }],
      category: 0,
      property: "",
    },
    {
      exploreQuery:
        `date=${startTime}%20${endTime}` +
        `&geo=${geo}` +
        `&q=${encodeURIComponent(keyword)}` +
        `&hl=en`,
      guestPath: "https://trends.google.com:443/trends/embed/",
    },
  );
}, [scriptLoaded, keyword, geo, startTime, endTime, type]);

Now, integrate the GoogleTrendsWidget into your application. Open your App.tsx file and import the GoogleTrendsWidget component.

import "./styles.css";
import GoogleTrendsWidget from "./GoogleTrendsWidget";

export default function App() {
  return (
    <div className="App">
      <h1>Google Trends Component for React</h1>
      <div>To use</div>
      <GoogleTrendsWidget
        keyword="Covid"
        geo="US"
        startTime="2019-01-01"
        endTime="2024-02-01"
      />
    </div>
  );
}

Conclusion

The key to the solution was to use renderExploreWidgetTo instead of the function provided by Google Trend’s website.

You can find a working example, with the entire GoogleTrendsWidget implementation at:

https://codesandbox.io/p/sandbox/google-trends-component-for-react-pvdr9x