How to add script with script tag in ReactJS?

Adding script with script tag is quite simple and easy in the JavaScript world. But when it comes to ReactJS then things are a little different compare to old JavaScript ways of doing it.

In ReactJS we have got multiple ways of adding script using the script tag. We can do it when a component is loading. We can add by using Helmet library of ReactJS.

Class component mount:

  componentDidMount() {
    const script = document.createElement("script");
    script.src = "https://thedomain/your.js";
    script.async = true;
    document.body.appendChild(script);
  }

Functional component mount:

  useEffect(() => {
    const script = document.createElement('script');
    script.src = "https://yourdomain/your.js";
    script.async = true;
    document.body.appendChild(script);
    return () => {
      document.body.removeChild(script);
    }
  }, []);

Functional component mount:

  import {Helmet} from "react-helmet";
  return (
    <div className="application">
      <Helmet>
        <script src="https://yourdomain/your.js"></script>
      </Helmet>
    </div>
  );
Reference:
Share