Implement 3rd Party Scripts in React JS

When building an web application using React JS we need to rely on various third-party scripts that need to be placed in ‘head’ or ‘body’ of our HTML. In some situations we need to load a library for that particular page, component or after the user’s particular action.

I was working on a project where I needed to send an API request which returns an ‘unique token’ for that particular session. So the token field in script tag was dynamic, which means it is changing for every session. Best way to implement it is using npm package, but in this case npm package is not available, so we can implement it in following way.

Implementation

Taking example of Place Picker API provided by MapMyIndia. In order to use JavaScript functions of Place Picker, we need to add script with a ‘unique token’ which is returned by base API call.

so, what we can do is as follows :

We are creating “script” element by using ‘document.createElement’ and src field is assigned to it. Then we are using appendChild method to append it in document.

Here, the base API call in implemented in ‘mapApi’ function and called it in componentDidMount and then the Place Picker API is called. While doing this Place Picker API can generate error if it is executed before the base API call as the token will not exist.

To avoid this, we can use await for calling the ‘mapApi’ function which will wait until the promise is resolved and then the Place Picker API gets called.

We can implement same with using ‘useEffect’ hook also

We are using same approach in useEffect hook. We are using await at line 5 so that it waits until the promise is resolved and then only Place Picker API gets called and the error is avoided.

In above code dependencies are none, hence useEffect hook will be executed only once. If you want it to execute every time a particular variable changes, then you can pass that variable in dependencies, i.e. in square braces at end of hook.

Conclusion

Thus, we can implement 3rd party scripts in a particular page or component in this way. We can also use npm packages if available to implement it smoothly

Programmer | React JS Developer | Python Developer