简体   繁体   中英

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.

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)
    })    
 }

Include the script tag in your index.html

Let's say if you want to include JQuery in your ReactJs app

Include following in index.html

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

Use this in following code and it works well

 import React, { Component } from 'react'; class App extends Component { constructor(){ super() this.callJquery = this.callJquery.bind(this); } callJquery(){ window.$("#sample").click(function(){ alert("Text: Button Clicked"); }); } render() { return ( <div className="App"> <div id="sample" onClick={this.callJquery}> Hellow </div> </div> ); } } export default App;

Similarly, you can use any library by including in index.html and then use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM