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 ?