0

I am trying to append a script tag to the head using React Component. From inspecting I see that the script tag has been added to the head but the content is not loaded on the page.

My code is:

export class TestComponent extends React.PureComponent<any, { loaded: boolean }> {
   state = { loaded: false };
   componentDidMount() {
      var s = document.createElement("script");
      s.async = true;
      s.src = "https://someurl/somejsfile.js";
      document.head.appendChild(s);
      s.onload = () => {
         this.state.loaded = true;
         console.log(s);
      };
   }
   render() {
      return null;
   }
}

This script tag adds a banner to the home page.

Cristiano Soares
  • 619
  • 1
  • 9
  • 20
Jilna
  • 190
  • 1
  • 13
  • Please see whether this (answered) thread my address your issue: https://stackoverflow.com/questions/30626030/can-you-force-a-react-component-to-rerender-without-calling-setstate I.e., either this.render(), this.setState() or this.forceUpdate() might do the trick. – Erik Reder Feb 18 '19 at 11:26
  • I added this `this.forceUpdate()` in `componentDidMount`. Did not work. Is this the right place to add it? Also from the link, I see that `this.forceUpdate` is not the right way to do it. – Jilna Feb 18 '19 at 11:34

0 Answers0