0

I have a React app created with create-react-app. Somebody gave me an external script to load, with three common jquery libraries. So I've searched a lot on the web to understand how to do it, but somehow, it doesnt' work.

My script can be found into the src/assets/js folder. And i use a tsconfig.json to make my base import url to "src" and I'm using react-router.

Method #1 - react-load-script - not working

I tried to load script with this library from NPM

function App() {
  return (
    <React.Fragment>
          <Script
            url="https://code.jquery.com/jquery-1.11.0.min.js"
          />
          <Script url="assets/js/myscript.js" />
          <SwitchRouter />
    <React.Fragment>
  );
}

Method #2 - homemade method with useEffect - not working

I tried to load script in a useEffect

function App() {
  const appendScript = scriptToAppend => {
      const script = document.createElement("script");
      script.src = scriptToAppend;
      script.async = true;
      document.body.appendChild(script);
    };

    appendScript("assets/js/myscript.js")
    appendScript("https://code.jquery.com/jquery-1.11.0.min.js")
  }, []);
  return (
    <React.Fragment>
          <SwitchRouter />
    <React.Fragment>
  );
}

Method #3 - In the index html - partially working

I tried to add directly the script in the public folder, and import it in the index.html, it work on the first load, but whenether you switch pages, the script isn't working anymore

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
</body>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="./myscript.js"></script>


</html>

So i'm kind of stuck because of this problem, have you an idea to explain why it is not working here ?

E. Donadei
  • 93
  • 1
  • 1
  • 5
  • What is you purpose. do you want to manipulate DOM which has been rendered by components or static index html elements? – Ahad Rafat Talebi Oct 24 '20 at 18:52
  • Just want to integrate this external script working with jquery, like it would work this class HTML / CSS – E. Donadei Oct 24 '20 at 19:44
  • This questioon (https://stackoverflow.com/questions/38518278/how-to-use-jquery-with-reactjs) will be useful. It is about using jQuery in react components. take a look. – Ahad Rafat Talebi Oct 24 '20 at 21:35

0 Answers0