Sitemap

Add External Script in React

2 Ways to use the external script with your React project.

--

Many times we want to use some external script with our React app. that can’t be installed by npm or yarn or we have script available locally or through CDN. Here is how you can easily use it in your React app.

Assume, you have your-script.js an external script.

And you want to use it in your React app. First of all, put it in the following location (you will have to create assets and js folder in public dir)

public/assets/js/your-script.js

Now there are 2 ways to load it

Direct Loading

Open public/index.html and add script tag above title tag.

...
<script type=”text/javascript” src=”./assets/js/your-script.js”></script>
<title>React App</title>
...

and you’re done.

Now you can use functions from your external script. You can’t directly use them. you’ll have to call them with window

Get Shivam Agrawal’s stories in your inbox

Join Medium for free to get updates from this writer.

Suppose there is a function name helloLife in your external script. you can call it like this in your React Components.

window.helloLife();

Drawback with the approach is we may not need this script everywhere in our React app. but we are unnecessarily loading it every time the app starts.

On-Demand Loading

Step 1. Install react-load-script component

npm install react-load-script --save

You can load your-script.js on-demand in your React component like this.

You want to use it in Demo component

Remember you’ll have to call the functions from your external script with window ( window.yourFunction(); )

Note: for script src, you can your local path or CDN URL.

Hope You Enjoyed the Journey.

Follow me on Github

--

--