How to Embed Google Trends into React app

2.7k Views Asked by At

I'm attempting to embed Google Trends into React so I can adjust the parameters dynamically. I can successfully embed it directly into the index.html file.

   <script
      type="text/javascript"
      src="https://ssl.gstatic.com/trends_nrtr/1644_RC01/embed_loader.js"
    ></script>
    <script type="text/javascript">
      trends.embed.renderExploreWidget(
        "TIMESERIES",
        {
          comparisonItem: [{ keyword: "/m/030q7", geo: "", time: "now 7-d" }],
          category: 0,
          property: ""
        },
        {
          exploreQuery: "q=%2Fm%2F030q7&date=now%207-d",
          guestPath: "https://trends.google.com:443/trends/embed/"
        }
      );
    </script>

However, I need to be able to change it via user input, so it needs to be in my jsx file. I've found a useful Helmet component to assist in adding scripts

  <Helmet>
    <script
      type="text/javascript"
      src="https://ssl.gstatic.com/trends_nrtr/1644_RC01/embed_loader.js"
    />
    <script type="text/javascript">
      {trends.embed.renderExploreWidget(
        "TIMESERIES",
        {
          comparisonItem: [
            { keyword: "/m/030q7", geo: "", time: "now 7-d" }
          ],
          category: 0,
          property: ""
        },
        {
          exploreQuery: "q=%2Fm%2F030q7&date=now%207-d",
          guestPath: "https://trends.google.com:443/trends/embed/"
        }
      )}
    </script>
  </Helmet>

but I'm getting such as

'trends' is not defined no-undef

I've tried adding 'this' and 'window' but get different errors.

Can anyone assist in helping me fix this?

EDIT

Although the proposed solution didn't work for me directly, I did manage to get it working properly by taking the generated iframe tag and implement this instead.

          <iframe
            id="trends-widget-2"
            src="https://trends.google.com:443/trends/embed/explore/TIMESERIES?req=%7B%22comparisonItem%22%3A%5B%7B%22keyword%22%3A%22bitcoin%22%2C%22geo%22%3A%22US%22%2C%22time%22%3A%22today%2012-m%22%7D%5D%2C%22category%22%3A0%2C%22property%22%3A%22%22%7D&amp;tz=-480&amp;eq=q%3Dbrexit%26geo%3DUS%26date%3Dtoday%2012-m"
            width="100%"
            height="300px"
            frameborder="0"
            scrolling="0"
          />
2

There are 2 best solutions below

2
On BEST ANSWER

First load the script url on your html file. Then use react-script-tag from npm and then write this on your component's render:

<ScriptTag type="text/javascript">
        {'trends.embed.renderExploreWidgetTo(
  document.getElementById('widget'),
  'TIMESERIES', 
  {'comparisonItem': [{'keyword':'chicken','geo':'','time':'today 12-m'}],'category':0,'property':''}, 
  {'exploreQuery':'q=chicken&date=today 12-m','guestPath':'https://trends.google.com:443/trends/embed/'}
)'}
</ScriptTag> 
3
On

I realize this question was posted some time ago, but I wanted to share a reusable component for Google Trends and how I embedded it in a react component in case it helps anyone in the future. I used react-load-script library in order to be able to load the script.

Here is the codesandbox:

https://codesandbox.io/embed/competent-cookies-v2kjz?fontsize=14&hidenavigation=1&theme=dark

And here is the code:

// App.js

import React from "react";
import GoogleTrends from "./GoogleTrends";
import "./styles.css";

export default function App() {
  return (
    <>
      <h1> Google Trends Example</h1>
      <p>
        Put the GoogleTrends comonent in a div with an id. Use the id, e.g.
        "widget" inside document.getElementById("widget") in the GoogleTrends
        component.
      </p>
      <div id="widget">
        <GoogleTrends
          type="TIMESERIES"
          keyword="Celine Dion"
          url="https://ssl.gstatic.com/trends_nrtr/2051_RC11/embed_loader.js"
        />
        <GoogleTrends
          type="GEO_MAP"
          keyword="Celine Dion"
          url="https://ssl.gstatic.com/trends_nrtr/2051_RC11/embed_loader.js"
        />
      </div>
    </>
  );
}

// GoogleTrends.js

import React from "react";
import ReactDOM from "react-dom";
import Script from "react-load-script";

export default function GoogleTrends({ type, keyword, url }) {
  const handleScriptLoad = _ => {
    window.trends.embed.renderExploreWidgetTo(
      document.getElementById("widget"),
      type,
      {
        comparisonItem: [{ keyword, geo: "US", time: "today 12-m" }],
        category: 0,
        property: ""
      },
      {
        exploreQuery: `q=${encodeURI(keyword)}&geo=US&date=today 12-m`,
        guestPath: "https://trends.google.com:443/trends/embed/"
      }
    );
  };

  const renderGoogleTrend = _ => {
    return <Script url={url} onLoad={handleScriptLoad} />;
  };

  return <div className="googleTrend">{renderGoogleTrend()}</div>;
}