How to use JQuery with ReactJS How to use JQuery with ReactJS jquery jquery

How to use JQuery with ReactJS


Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.

step 1: Go to your project folder where the package.json file is present via using terminal using cd command.

step 2: Write the following command to install jquery using npm : npm install jquery --save

step 3: Now, import $ from jquery into your jsx file where you need to use.

Example:

write the below in index.jsx

import React from 'react';import ReactDOM from 'react-dom';import $ from 'jquery';//   react code here$("button").click(function(){    $.get("demo_test.asp", function(data, status){        alert("Data: " + data + "\nStatus: " + status);    });});// react code here

write the below in index.html

<!DOCTYPE html><html><head>    <script src="index.jsx"></script>    <!-- other scripting files --></head><body>    <!-- other useful tags -->    <div id="div1">        <h2>Let jQuery AJAX Change This Text</h2>    </div>    <button>Get External Content</button></body></html>


You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.

e.g.

class App extends React.Component {  componentDidMount() {    // Jquery here $(...)...  }  // ...}

Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.

class Accordion extends React.Component {  constructor() {    super();    this._handleClick = this._handleClick.bind(this);  }  componentDidMount() {    this._handleClick();  }  _handleClick() {    const acc = this._acc.children;    for (let i = 0; i < acc.length; i++) {      let a = acc[i];      a.onclick = () => a.classList.toggle("active");    }  }  render() {    return (      <div         ref={a => this._acc = a}         onClick={this._handleClick}>        {this.props.children}      </div>    )  }}

Then you can use it in any component like so:

class App extends React.Component {  render() {    return (      <div>        <Accordion>          <div className="accor">            <div className="head">Head 1</div>            <div className="body"></div>          </div>        </Accordion>      </div>    );  }}

Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110(I changed this link to https ^)


Step 1:

npm install jquery

Step 2:

touch loader.js 

Somewhere in your project folder

Step 3:

//loader.jswindow.$ = window.jQuery = require('jquery')

Step 4:

Import the loader into your root file before you import the files which require jQuery

//App.jsimport '<pathToYourLoader>/loader.js'

Step 5:

Now use jQuery anywhere in your code:

//SomeReact.jsclass SomeClass extends React.Compontent {...handleClick = () => {   $('.accor > .head').on('click', function(){      $('.accor > .body').slideUp();      $(this).next().slideDown();   });}...export default SomeClass