2

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.

2
  • Does this answer your question? Adding script tag to React/JSX Commented Feb 12, 2020 at 21:15
  • thanks Juan, I edited my question to say, my code was correct & the issue was related to cookie. Thanks Commented Feb 13, 2020 at 12:14

1 Answer 1

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);
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for looking into this, however, this didn't work. If it was in head, I could use React-helmet package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.