How can I include a JS script in a ReactJS page?

Viewed 347

I made a simple quiz using JS to be used in a page of my react app. The thing is, I don't know how to include it inside the page file. How do I do so?

3 Answers

There's a couple of different ways you could do this. You could use react-helment and add the script in a scriptTag like so:

import {Helmet} from "react-helmet";
const Demo = props => (
        <div>
            <Helmet>
              <script src="/path/to/resource.js" type="text/javascript" />
            </Helmet>
            ...
        </div>
);

That is probably the simplest way, but there are other libraries and resources you could use like useEffect from react, or appendScript from utils. You can also add it as a script tag in the head of your base html file and call it from your componentDidMount() function.

HTML for scripts on a page is usually some permutation of:

<script type="text/javascript" src="/path/to/your/script.js"></script>

or

<script type="text/javascript">
/*
All your javascript inline here
*/
</script>

These are usually either inside the <head> tag of the page, if it must execute before everything else or just before the </body> tag, if it relies on the page markup.

I was using npm react-script-tag npm link yesterday and it was working pretty good. Its pretty easy to use as well as Helmet like another user suggested.

Related