Rahul
Rahul

Reputation: 99

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.

Upvotes: 5

Views: 12762

Answers (2)

Chemah
Chemah

Reputation: 638

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

Upvotes: 11

Harsh Makadia
Harsh Makadia

Reputation: 3433

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.

Upvotes: -3

Related Questions