0

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?

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

1 Comment

@Stophface — You need to use a URL to your script. You can't use a URL hosted by the react dev server. That doesn't deal with serving static files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.