admin管理员组

文章数量:1129437

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?

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?

Share Improve this question edited May 10, 2019 at 20:37 jarrodwhitley 82812 silver badges30 bronze badges asked Jul 22, 2016 at 4:40 ND.SantosND.Santos 1,5332 gold badges10 silver badges5 bronze badges 3
  • 18 please, try to not use jQuery inside react... – quirimmo Commented Dec 23, 2018 at 16:23
  • 5 See reactjs.org/docs/integrating-with-other-libraries.html with explanation why it is not recommended to use jQuery inside react. From stackoverflow.com/a/46946447/52277 – Michael Freidgeim Commented Oct 17, 2019 at 21:05
  • 3 this is shatnez! avoid it :D en.wikipedia.org/wiki/Shatnez – Joey Baruch Commented Aug 11, 2020 at 4:56
Add a comment  | 

13 Answers 13

Reset to default 244

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>

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

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

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

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';

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

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

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

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();`
    });
}

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.

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/

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

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

本文标签: javascriptHow to use JQuery with ReactJSStack Overflow