I wonder how I would add an external script to an React
application and make its functions available. Let's take this script https://www.cssscript.com/confetti-falling-animation/
In a "not-react-application" I would add it like this in my DOM
<script src="confetti.js"></script>
and then call it's functions like this
startConfetti();
or
stopConfetti();
However, this does not work in React
. I know that I can add a <script />
tag like this:
useEffect(() => {
const script = document.createElement('script');
script.src = './confetti.js';
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
But this does not make the functions startConfetti()
or stopConfetti()
available. They are undefined
.
How would I add the script and its functionalities in a React
App?
CodePudding user response:
Add the script in index.html
's head tag, like so (with the correct path to the JavaScript file):
<script src="confetti.js"></script>
Then in your React component, you could get it with the help of window
object, this way:
const startConfetti = window.startConfetti;
startConfetti();