Load External Script From Advertising Partner in React.js app

Viewed 1252

I want to include two types of ads into my React.js Web app

<script async="async" data-cfasync="false" src="//somewebstite.com/invoke.js"></script>
<div id="container-4foobarbaz"></div>

and this ad as well:

<script type="text/javascript">
atOptions = {
    'key' : 'somekey',
    'format' : 'iframe',
    'height' : 250,
    'width' : 300,
    'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.cdnwebsite.com/invoke.js"></scr' + 'ipt>');

How Can I include this in my React App? I have tried a few things but none have them have worked including:

    const script = document.createElement("script");
    script.async = true;
    script["data-cfasync"] = true;
    script.src = "//somewebstite.com/invoke.js"

    this.div.appendChild(script); 

and this in the render:

<div id="container-4foobarbaz" ref={el => (this.div = el)} >

  </div> 
2 Answers

I saw you're trying to use adsTerra, so here is a working example (in Typecript)

import { useEffect, useRef } from 'react'
export default function Banner(): JSX.Element {
    const banner = useRef<HTMLDivElement>()

    const atOptions = {
        key: 'YOUR_KEY',
        format: 'iframe',
        height: 50,
        width: 320,
        params: {},
    }
    useEffect(() => {
    if (!banner.current.firstChild) {
        const conf = document.createElement('script')
        const script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = `//www.highperformancedformats.com/${atOptions.key}/invoke.js`
        conf.innerHTML = `atOptions = ${JSON.stringify(atOptions)}`

        if (banner.current) {
            banner.current.append(conf)
            banner.current.append(script)
        }
    }
}, [])

    return <div ref={banner}></div>
}

You can use this example code. The idea behind this is to import ads script when the component is mounted and initialize the ads. Every time the component remount to the DOM, it won't import the already imported ads script. I also create an example for you on Codesandbox here: https://codesandbox.io/s/example-react-google-ads-0b700

  componentDidMount() {
    // inject some code to head element
    const head = document.querySelector("head");
    // import google ads script if not yet imported
    if (!head.querySelector("#my-google-ads-1")) {
      const script = document.createElement("script");
      script.id = "my-google-ads-1";
      script.async = true;
      script.src = "https://www.google.com/adsense/search/ads.js";
      head.appendChild(script);
    }
    // add another script to head element
    if (!head.querySelector("#my-google-ads-2")) {
      const script = document.createElement("script");
      script.id = "my-google-ads-2";
      script.type = "text/javascript";
      script.charset = "utf-8";
      script.innerHTML = `
        (function(g,o){g[o]=g[o]||function(){(g[o]['q']=g[o]['q']||[]).push(
        arguments)},g[o]['t']=1*new Date})(window,'_googCsa');
      `;
      head.appendChild(script);
    }

    // init ads
    var pageOptions = {
      "pubId": "pub-9616389000213823", // Make sure this the correct client ID!
      "query": "hotels",
      "adPage": 1
    };

    var adblock1 = {
      "container": "afscontainer1",
      "width": "700",
      "number": 2
    };

    window._googCsa('ads', pageOptions, adblock1);
  }

  render() {
    return (
      <div className="App">
        <h1>Hello React.js</h1>
        <h2>These are sample ads</h2>
        <div id='afscontainer1'></div>
      </div>
    );
  }
Related