How to use JavaScript libraries not in npm – Reactjs

This a common problem. There are many ways you can fix this. First of all I will explain the problem. This may happen if you use webpack to bundle all the libraries into one file and using react-router to load pages or using any other technique.

There are many awesome JavaScript libraries that are not in NPM (Node Package Manager). For example if there is an library that gives you beautiful photo slider and that library needs certain HTML tags with an “id” value to format or to apply styles create beautiful photo slider. So you had to add that external library to .html or to template file like .ejs. When you load that html tags using Reactjs you can see that beautiful photo slider may not work. The cause for that is DOM loads later and that external library loads first. You have to run external library function after Reactjs loads the DOM. How to do that.

You can append that external library as shown below

componentWillMount() {
        const script = document.createElement("script");
        script.src = "https://www.example.com/foobar.js";
        script.async = true;
        document.body.appendChild(script);
    },

You can use react-helmet library to load external libraries. React Helmet library support server side rendering too. Using that library you can set title, meta, link, script tags and etc. This is my recommended way.

Install react-helmet from npm

npm install --save react-helmet

Apply below code in react render function

import {Helmet} from "react-helmet";
    <Helmet>
            <title>My Title</title>
            <script src="/assets/js/custom.js" type="text/javascript" />
          </Helmet> 

Please don’t forget to comment. If you have any other best way of doing that please leave a comment.

Leave a Comment