1

I need to add a div & async script at the bottom of the page in my react application.

1st Try:

  ...
  ...
  render() {
    return (
      <div>
        <HeaderComponent />
        <Notifications />
        {children}
        <FooterComponent />
        <div
          className="cc-banner-embed"
          data-config="YmFja2MGVUJhY2tncm91bmQ9dHJ1ZQ==">
          <script async src="https://banner.crowdcube.com/embed.js"></script>
        </div>
      </div>
    );
  }

2nd Try:

  ...

  // use lifecycle method to load script
  componentDidMount() {
    const s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://banner.crowdcube.com/embed.js";
    this.instance.appendChild(s);
  }

  render() {
    return (
      <div>
        <HeaderComponent />
        <Notifications />
        {children}
        <FooterComponent />
        <div
          className="cc-banner-embed"
          data-config="YmFja2MGVUJhY2tncm91bmQ9dHJ1ZQ=="
          ref={el => (this.instance = el)}>
        </div>
      </div>
    );
  }

Unfortunately, both of these didn't work. How do I get this script file to load async.

EDIT: My code was actually correct, however, in this case, the browser for some reason wasnt displaying it (cookie issue maybe). Going in incognito did the trick. Thank you.

Kayote
  • 14,579
  • 25
  • 85
  • 144
  • Does this answer your question? [Adding script tag to React/JSX](https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx) – Juan Marco Feb 12 '20 at 21:15
  • thanks Juan, I edited my question to say, my code was correct & the issue was related to cookie. Thanks – Kayote Feb 13 '20 at 12:14

1 Answers1

1

You can try this to load your script to your react app

  componentDidMount() {
    const head = document.querySelector('head');
    const script = document.createElement('script');
    script.setAttribute('async',true);
    script.setAttribute('src', 'https://banner.crowdcube.com/embed.js');
    head.appendChild(script);
  }
rajan tank
  • 217
  • 1
  • 3
  • Thank you for looking into this, however, this didn't work. If it was in `head`, I could use React-helmet package. – Kayote Feb 12 '20 at 13:36