'how to add external library to reactjs?

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.



Solution 1:[1]

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

Solution 2:[2]

  1. Easiest way is to find out whether your external library has an npm module, if so you can simply do an npm install.
  2. Else you can add the link to this library in your index.html.
  3. Otherwise you can download the files of your external library and use it inside as if its your own code(better checkout whether its free library to do that). In this case you can simply import the file

Solution 3:[3]

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"

Solution 4:[4]

You can use like that :

import abc from './abc.js'

Check here : How to include external javascript library in reactjs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tico
Solution 2 Rohith Murali
Solution 3 Native Coder
Solution 4 Jagjeet Singh