How to Include Third Party Js Libraries in React App

How to insert a 3rd party library in ReactJS app

The solution is:

First, add this inside index.html

<script type="text/javascript" src="libs/kaiads.v4.min.js" defer></script>

Then, call the function like this: window.getKaiAd

Import third-party JavaScript library that normally self-executes into React app (using create-react-app)

I was able to get this working by directly importing the file from the library's dist folder, instead of just naming the library by itself.

I also needed to make sure to import the library first before any other libraries (e.g. React).

App.js

import "some-library/dist/some-library.js";
import React, { Component } from "react";
...

How do I use/include third party libraries in react?

You have two options, both demonstrated by a contrived example where I fade out a unordered list using jQuery. There are pros and cons to both approaches, I highlight both, and then provide my choice.

Option 1: Include the third party library in your index.html file

index.html

<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
...
</head>

App.jsx

import React, { Component } from "react";

class App extends Component {
componentDidMount() {
// ** following two lines of code do the same thing
// using the first version, however, could potentially cause errors
// see "Referencing unimported libraries when using create-react-app"
$(this.refs.list).fadeOut(); // version 1
window.$(this.refs.list).fadeOut(); // version 2
}

render() {
return (
<ul ref="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
);
}
}

ReactDOM.render(<App />, document.getElementById("root"));

Referencing unimported libraries when using create-react-app

** If you are using create-react-app to scaffold your project, using the first version of code will throw errors. This is because create-react-app's default syntax linter (eslint) will throw errors during project compilation if you try to reference non-imported code (i.e. you never import $ from "jquery" since we reference the library in index.html). So when we referencing jQuery's global $ reference (which is very normal when using jQuery in the browser), we violate the basic principles of building modular JavaScript applications on Node.js. In Node, modules are the way of life and in those modules, we can only reference objects that we explicitly import. Without that explicit mention we technically break convention, hence the complaint from the linter.

Now both you and I know that the $ reference will become available once the application actually runs in the browser. When componentDidMount() is invoked, view has already mounted to the DOM and your third party library (in our example jQuery) is available to reference. Unfortunately the linter will block your react app from rendering because it thinks you are trying to reference undefined variables. Furthermore, the linter is platform agnostic and has no knowledge that your app is running in the browser (since JavaScript is no longer a browser-only language). This may be annoying but the linter is just doing its job, and, to some degree, it's absolutely right.

To avoid this error there are a few options:

  1. Have eslint (the provided linter) ignore the lines where you make
    reference the third party libraries using // eslint-disable-next-line (not preferred)
    , or
  2. Make use of window (preferred), or
  3. Turn off the linter (not preferred), or
  4. Don't use create-react-app (your preference, not recommend for beginners or even experts for that matter).

The first option can easily become a hassle if you make a lot of calls to the third party library. If you read up on componentDidMount, you know that at this point of invocation, you now have access to the window variable. You can access your library through window if the library attaches itself to the DOM's global window object. In our example, jQuery does just that and we can access jQuery's functionality via window.$

Option 2: Install the library using npm install <package-name> -S and import the library into relevant project files.

Terminal

npm i jquery -S

App.jsx

import React, { Component } from "react";
import $ from "jquery";


class App extends Component {
componentDidMount() {
$(this.refs.list).fadeOut();
}

render() {
return (
<ul ref="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
);
}
}

ReactDOM.render(<App />, document.getElementById("root"));

What is the right approach?

There are pros and cons of each approach: with first one you have the possibility of using a library that is hosted on a CDN and bank on the network effects and don't need to import third party code into your codebase. With the latter, you can make your code more readable and avoid the linter from blowing up.

For cons, the first approach may require you to add window to your third party library calls if you're using a linter (and you probably should); in the latter's case, sometimes third party libraries don't have their project code available to install through npm and you must download them manually and manually add them to your project source folder. In that case, using the first approach might make sense so that you don't have to manually import new versions of the library when they're released.

If at the end of all of this, you have failing code:

  • Ensure you installed the correct package,
  • Ensure you have included it directly in your index file or
    imported it into your project and files where you are making library
    specific calls.

If you know of other ways of accomplishing third party library integrations into react or find an error in this post, please feel free to edit this answer or add another answer.

The examples in this answer assume the execution environment is a browser, hence the use of window. If you are building a shell script or using react-native, it would be global, etc.

It is possible to import a third-party js file in react app?

You can get access to any variables defined using var on others scripts (connected before your script and unlabelled like async).

Well, if you connect your js file before your react-app code you can access all variables declared using var.

For example

index.html

<html>
...
<body>
<script src="js-file.js" />
<script src="react-code.js" />
</body>
</html>

js-file.js

var mySharedVariable = "Example";

react-code.js it's webpack bundle (js result of npm run build)

...
export class MyComponent extends Component {
render() {
return mySharedVariable;
}
}
...

MyComponent will render string "Example"

If you use typescript you must declare mySharedVariable before using like

declare let mySharedVariable: string;

Why you can't use async script? You can read this article

UPD

So, lets do it together step-by-step

1) Create react app using cra

npx create-react-app my-app

2) Create file external.js and put it in public folder (next to the index.html) (If you have remote file pass this step)

var external = "external";

3) Modify your index.html file (append one line before closing body tag)

<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->

<!-- src is path to your js file -->
<script src="external.js"></script> <!-- add this line -->
</body>

4) Modify your App.js file

import React from 'react';
import './App.css';

function App() {
return (
<h1>{external}</h1>
);
}

export default App;

5) Lets start your app

npm run start

add third-party js library to Create React App

You can use it in the following way:

function loadScript(url, callback){

let script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
callback();
};
}

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

and then use this function on componentDidMount() to load the external script.

How to Integrate third party libraries into React JS

In public folder add the following code in of the index.html page.

 <base href="/">


Related Topics



Leave a reply



Submit