1

I am dynamically appending scripts to my react app like this

    export const appendScript = (scriptToAppend : string) => {
    const script = document.createElement("script");
    script.src = scriptToAppend;
    script.async = true;
    script.type = "text/jsx"; 
    document.body.appendChild(script);
}

App Component

class App extends React.Component {

  componentDidMount() {   
     appendScript("./assets/custom.min.js");
  } 
}

custom.min.js file

$(document).ready(function(){
    alert("ready");
})
Favour Emmanuel
  • 73
  • 3
  • 10
  • You are mixing up multiple things. if you're having Single Page Application then open up the `index.html` and add the `script` after the `body` tag OR `defer` the execution of this `javascript`. `React` is for creating reusable components, understand the purpose. – Parag Diwan Feb 26 '22 at 13:51

1 Answers1

1

Check the answer in https://stackoverflow.com/a/34425083/13558764.

Or you can try "react-helmet" package.

Here is a sample usage.

import React from "react";
import {Helmet} from "react-helmet";

class Application extends React.Component {
  render () {
    return (
        <div className="application">
            <Helmet>
                <script src="https://use.typekit.net/foobar.js"></script>
                <script>try{Typekit.load({ async: true });}catch(e){}</script>
            </Helmet>
            
        </div>
    );
  }
};
Hik Hik
  • 31
  • 5
  • I think react-helmet make it easy for beginners, also makes it easy to add multiple js files. – Hik Hik Mar 08 '22 at 12:22
  • Loading JavaScript Files The problem with this approach is that it's hard to control when a particular script got loaded. Errors during loading are hard to process as well. For dynamically loading JavaScript files we may use the [Code Splitting](https://reactjs.org/docs/code-splitting.html) and [React.lazy](https://reactjs.org/docs/code-splitting.html#reactlazy). For server-side rendering, we may use [Loadable Components](https://loadable-components.com/). Refer to this [Article](https://www.newline.co/@dmitryrogozhny/when-to-use-and-when-to-avoid-using-react-helmet--bf6f62d5) – Hik Hik Mar 08 '22 at 12:37