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:
This command sets up a new React application and starts a development server.
Create the Google Trends Widget Component
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.
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.
Loading the Google Trends Script
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.
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.
Using the Google Trends Widget Component
Now, integrate the GoogleTrendsWidget
into your application. Open your App.tsx
file and import the GoogleTrendsWidget
component.
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