Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React, how to add external script and make its functions available?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading