Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use external js files in reactjs

I am trying to convert bootstrap 4 template into reactjs bootstrap is working fine but there are other javascript plugins also and I don't know how to use . Any suggestions would be appreciated.

like image 494
Rahul Avatar asked Mar 11 '18 14:03

Rahul


People also ask

How to append an external JS file in react?

If you are a fan of Hooks in React, then useEffect is a great way to append external JS files. You can read my article on using the Effect Hook. To give a gist useEffect is similar to componentDidMount and componentDidUpdate life cycle methods in React class components. If your effect returns a function, React will run it when it is time ...

How to import the script inside the React component?

If you want to import the script inside the react component, you can use the following options. Show activity on this post. You can add External JS library in indeex.html page inside public directory.

How to include external JavaScript library in react-script-tag?

The react-script-tag is a package that comes up with a <script> tag that supports universal rendering. With the help of this library, we can directly append the <script> tag to our document. And inside the ‘src’ attribute of the script tag, we can include the URL of the external JavaScript library.

How do I add a script tag to a React project?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. npm install --save react-script-tag Import ‘ScriptTag’ component: Import the built-in ‘ScriptTag’ component from the react-script-tag library at the top of the file where we want to add the script tag.


1 Answers

Update: Please, don't mix jQuery and React. It could be difficult to handle the DOM and VirtualDOM. Just try it if you really need to:

Try to invoke the scripts and append it when componentDidMount at Root component. Here is a snippet:

//#Write some like this in the App.js for example, since it's the main component:
componentDidMount(){
    //An array of assets
    let scripts = [
        { src: "assets/vendor/jquery/jquery.js" },
        { src: "assets/vendor/bootstrap/js/bootstrap.js" },
        { src: "assets/vendor/jquery-placeholder/jquery.placeholder.js" },
        { src: "assets/javascripts/theme.js" },
        { src: "assets/javascripts/theme.custom.js" },
        { src: "assets/javascripts/theme.init.js" }
    ]
    //Append the script element on each iteration
    scripts.forEach(item => { 
        const script = document.createElement("script")
        script.src = item.src
        script.async = true
        document.body.appendChild(script)
    })    
 }
like image 199
Chemah Avatar answered Sep 22 '22 20:09

Chemah