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&tz=-480&eq=q%3Dbrexit%26geo%3DUS%26date%3Dtoday%2012-m"
width="100%"
height="300px"
frameborder="0"
scrolling="0"
/>
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>