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> <div>Head 1</div> <div>Body 1</div> </div> <div> <div>Head 1</div> <div>Body 1</div> </div> <div> <div>Head 1</div> <div>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?

5

12 Answers

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> <h2>Let jQuery AJAX Change This Text</h2> </div> <button>Get External Content</button> </body> </html> 
3

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:

5

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 
0

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

0

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

1

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.

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:

$('.simpleCart_input').blur(function() { var val = $.trim(this.value); $(this).wrap($('<span/>', { 'class': $(this).attr('class'), html: val })).remove(); });
<script src=""></script> <script src=""></script> <input type="text" />

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy