142

I'm new to ReactJS. Previously I've used jQuery to set any animation or feature that I needed. But now I'm trying to use ReactJS and minimize the use of jQuery.

My Case is:

I'm trying to build an accordion with ReactJS.

<div class="accor">
   <div class="head">Head 1</div>
   <div class="body hide">Body 1</div>
</div>
<div class="accor">
   <div class="head">Head 1</div>
   <div class="body hide">Body 1</div>
</div>
<div class="accor">
   <div class="head">Head 1</div>
   <div class="body hide">Body 1</div>
</div>

using JQuery:

$('.accor > .head').on('click', function(){
   $('.accor > .body').slideUp();
   $(this).next().slideDown();
});

My Question:

How can I do this with ReactJS?

jarrodwhitley
  • 826
  • 10
  • 29
ND.Santos
  • 1,443
  • 2
  • 10
  • 5

13 Answers13

239

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
npm i --save-dev @types/jquery

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>
Dani
  • 3,128
  • 2
  • 43
  • 91
solanki...
  • 4,982
  • 2
  • 27
  • 29
  • 5
    While this answer may be technically correct, in my opinion it doesn't do enough to remind readers that [direct DOM manipulation with vanilla JS or jQuery in the context of an MV* library like React is **almost always an antipattern**](https://stackoverflow.com/a/51304632/6831341). – Alexander Nied May 19 '22 at 14:21
102

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mnsr
  • 12,337
  • 4
  • 53
  • 79
  • 1
    Thx jzm.. But I still need information about your code. I don't quite get what it' mean. Can you explain about this: 1. **ref={a => this._acc = a}** 2. **let** 3. **this._acc.children** Thanks 4 your help :) – ND.Santos Jul 22 '16 at 06:43
  • 1
    @ND.Santos Read this page: https://facebook.github.io/react/docs/more-about-refs.html that's the callback ref syntax. So instead of ref="accordion" or whatever, you use what i use and it returns the node. string ref is considered legacy. this._acc = calling the node ref (ie, you create a sort of variable which references the node - so you can call it whatever you want). 'children' is the children elements inside ``. In my codepen link, you can add `console.log(this._acc)` to see what it actually is. – mnsr Jul 22 '16 at 07:48
  • Nice @mnsr Can you explain the reason for using the componentDidMount() method there? – Eddie Lam Jun 17 '20 at 01:01
  • 5
    Why should you avoid trying to use them together? – Sam Mar 05 '21 at 19:27
  • 2
    @Sam Was wondering the same thing and found the answer to [that question](https://stackoverflow.com/a/51304632). – Bartleby Oct 24 '21 at 15:14
30

Step 1:

npm install jquery

Step 2:

touch loader.js 

Somewhere in your project folder

Step 3:

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

Step 4:

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

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

Step 5:

Now use jQuery anywhere in your code:

//SomeReact.js
class SomeClass extends React.Compontent {

...

handleClick = () => {
   $('.accor > .head').on('click', function(){
      $('.accor > .body').slideUp();
      $(this).next().slideDown();
   });
}

...

export default SomeClass
David Joos
  • 926
  • 11
  • 16
12

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

hardik chugh
  • 1,082
  • 15
  • 12
7

To install it, just run the command

npm install jquery

or

yarn add jquery

then you can import it in your file like

import $ from 'jquery';
Guru Prasad mohapatra
  • 1,809
  • 13
  • 19
1

I read a lot about jQuery and ReactJS; they have been always advised to avoid using jQuery in ReactJS apps.

If you want to create an accordion, you can do it with React-Bootstrap: React-Bootstrap Accordion Component

Hessah
  • 192
  • 3
  • 12
  • 1
    This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30050575) – Shaurya Vardhan Singh Oct 11 '21 at 16:34
1

React jquery plugin is a node package that will help you using jQuery plugins easily with ReactJs.

npm i react-jquery-plugin 

or

yarn add react-jquery-plugin

USAGE:

import React, { useEffect } from 'react'
import { $ } from 'react-jquery-plugin'
export default function App() {

    //if you're using LifeCycle methods
    // componentDidMount() {
    //     $(window).scroll(() => {
    //         // put your code here
    //     });
    // }

    // With lifeCycle Hooks
    useEffect(() => {
        $(window).scroll(() => {
            // put your code here
        });

    }, [])

    return (
        <div>
            <h1>Hello React with jQuery</h1>
        </div>
    )
}
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Anis
  • 77
  • 2
  • 7
0

I was tried bellow script and its work fine for me.

  1. Install jQuery : npm install jquery
  2. Import $ from jQuery : import $ from "jquery";
  3. Write bellow code on Component Did Mount Method
componentDidMount() {
    $(document).on('click','.accor >  .head',function(){
        `var closestDiv = $(this).closest('.accor');`
        `closestDiv.find('.body').slideToggle();`
    });
}
Naresh Goyani
  • 39
  • 2
  • 8
0

You can use JQuery with React without doing:

import $ from 'jquery'

To do so, you need to go to the root folder where package.json in your terminal and type this command:

yarn add -D expose-loader

Then add this configuration to your webpack.config.js file:

  module: {
    rules: [ 
      {test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery'}
    ]
  }

This exposes $ and jQuery to the global scope, so you can use them anywhere in your code.

Don't forget to add Jquery to your vendor bundle like this:

module.exports = config({
  entry: {
    vendor: [ 
      'jquery'
    ]
  }
...

Now you can use jquery without importing it inside your code because that's what expose-loader does for you.

And to test that it works just fine, add this to any file in your project:

console.log($);

and see in your browser console that it will show you the $ variable without throwing an error.

0

use a style library like bootstrap or MUI to accomplish this. react has react strap, a solid bootstrap/react component package. the style frameworks can both be used but it is not a good practice to mix them. I would recommend using react strap as i believe it has better react components, personal preference.

if you continue in react, you will find that jquery is not the best solution. it may work but since react and jquery are bothing working from the dom (and react manages a shadow dom) you might have issues. someone had mentioned using the react lifecycles to use the library on mount or load. for those of us using the newer functional components & hooks (react 16+ i believe) we can use the useEffect hook to call it on load.

useEffect(() => {
  // use jquery here if you must, this way the component is loaded 
  //and the dom matches whats in react (or should)
}, []);

the style and component libraries are best practice. for the same reason you would use formik to manage a form component (to not have to re-create the wheel/form every time) the same is true for the style component libraries.

https://www.npmjs.com/package/reactstrap

https://getbootstrap.com/docs/5.0/components/accordion/ https://mui.com/components/accordion/

sao
  • 1,835
  • 6
  • 21
  • 40
0

Best is not to mix React and jQuery if you require it for any jQuery plugins. It will not work as event handlers (like onclick) in jQuery do no work.

See excellent answer here: What is the right way to use Jquery in React?

If you really have to mix the two, read here: https://reactjs.org/docs/integrating-with-other-libraries.html

pizzamonster
  • 1,141
  • 10
  • 9
0

install: npm install jquery --save npm i --save-dev @types/jquery

in jsx file: import $ from 'jquery';

don't use $(document).ready() function The rest is the same as in jQuery. Put jQuery function within a function or useEffect hook

Gennadij
  • 1
  • 1
-1

If you need to add jQuery code for all your React App then you should add the jQuery in componentDidMount() lifecycle function of the component:

class App extends React.Component {
  componentDidMount() {
    // Jquery Code for All components of the React App
  }
}

But, if you need to use jQuery code in each component in the App, you should put your code in the useEffect()

const ComponentExample = () => {

  useEffect(() => {
    // Jquery Code for this component
  })

  return (
    <div>
        <h1></h1>
    </div>
  )
}
Astro
  • 641
  • 2
  • 6
  • 13