javascript

jquery

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?

Solution 1

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>

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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

Solution 6

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

Solution 7

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

Solution 8

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.

Solution 9

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/

Solution 10

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

Solution 11

$('.simpleCart_input').blur(function() {
  var val = $.trim(this.value);
  $(this).wrap($('<span/>', {
    'class': $(this).attr('class'),
    html: val
  })).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="simpleCart_input" style="background-color:yellow; color:balck; border-radius:6px; height:90px; width:100px;" />

Solution 12

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