Skip to content

Instantly share code, notes, and snippets.

@ShuvoHabib
Created April 2, 2022 19:32
Show Gist options
  • Save ShuvoHabib/d69791fe4e7e78c414ef4575524054fb to your computer and use it in GitHub Desktop.
Save ShuvoHabib/d69791fe4e7e78c414ef4575524054fb to your computer and use it in GitHub Desktop.
Using jQuery in React [jQuery setup in React]

Since React uses the Virtual DOM to manipulate the DOM nodes on the web page, and most other libraries might do direct DOM manipulation, variable attached to window is not directly available to all components. Thus in every component where jquery is required, a variable('$' to follow the convention) has to set equal to window.$ as shown in step 4

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 can create $ variable

// SomeReact.js
import '<pathToYourLoader>/loader.js'
const $ = window.$

Step 5:

Now use jQuery anywhere in your component:

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

...

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

...

export default SomeClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment