Reputation: 91
what are the various options to add an external JS library to reactjs component? for example, if we have any library file such as example.js and it is used by only one react component then i would like to either add this library at index.html or at the component level. I would like to know how to include at component level.
Upvotes: 2
Views: 12201
Reputation: 157
You can create a component that inserts the script to the header of your site. For example:
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
const ExternalLibrary = () => {
useEffect(()=>{
if (typeof window !== "undefined"){
// Make sure it only gets included once.
if (!document.getElementById("externalLibrary")){
const script = document.createElement('script');
script.id='externalLibrary'
script.type = 'text/javascript';
script.src = `https://externallibrary.com/example.js`;
// Call some function from the library when it loads.
script.onload = function() {
window.someFunction()
};
document.getElementsByTagName("head")[0].appendChild(script);
}
}
}, []);
return null;
}
export default ExternalLibrary;
Then you can just include this in your App.js, or other components.
Upvotes: 1
Reputation: 1870
Hosted Client-Side Libraries
If you want to import a client-side hosted library your only option is to include it in index.html
For instance, if we wanted to include D3 in one of our components, we could add <script src="https://d3js.org/d3.v5.min.js"></script>
to /public/index.html
Then to use it from inside your component, you need to call window.d3
instead of just d3
Non-Hosted client-side libraries
If you have a library that is not hosted, you could always save it to it's own file. once you do that, simply import it like you would any other local file import some_library from "./path/to/some/library"
Upvotes: 4
Reputation: 5669
npm install
. index.html
. import
the fileUpvotes: 0
Reputation: 2950
By "external libraries" I'm assuming you're talking about npm
/yarn
repository libraries, for example:
$ npm install moment
(Moment.js)
In those cases, you want to import it as:
import moment from 'moment'
Another example from the same package can be seen here
Upvotes: 0
Reputation: 1572
You can use like that :
import abc from './abc.js'
Check here : How to include external javascript library in reactjs
Upvotes: -1