Reputation: 971
I am adding image slider library in my react app. It is working but I am not sure whether it is the only way or not.
Inside my react.js file, I did this:
componentDidMount() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'js/banner.js';
head.appendChild(script);
}
and in the banner.js
file I have added the code for slider
and the code for library is added in index.html
file as a script tag. I know it is adding the js file multiple times but i don't know another way to add it
It is working absolutely fine but I am not sure it is the right way
Upvotes: 2
Views: 1729
Reputation: 1980
Andy's comment is correct, you should include your libraries through npm
when possible. To do this, google the package to find it's name in the npm registry.
You can then run npm install --save banner
(assuming the package name you found is banner
) to automatically save the library to your package.json
. This way any time you run npm install
or npm update
, the package will be taken care of via npm
.
In your .jsx
file where you create your React component, you can add this to the very top:
// if you're not using ES6
const banner = require('banner')
// if you are
import * as banner from 'banner';
// if the package exports modules
import {banner} from 'banner';
If the library doesn't exist as a package on the npm
registry, you can still do this in pretty much the same way. You will just need to add the .js
file for the library to your project and use a relative path to require
/import
(i.e. require('../../vendor/banner.js')
).
Upvotes: 3