How to install jquery in react?

How to use jquery in react?
Need to install jquery as : F:\react\cusotmjquery>npm install jquery

Also, you can use this command npm i jquery

When you will use the above command then install latest version jquery otherwise need to define what specific version you need to install as this command: npm install jquery@2.2.1

Then need to check at "package.json" file this code:
"dependencies": {
    "jquery""^3.4.1", // here will be shown
    "react""^16.11.0",
    "react-dom""^16.11.0",
    "react-scripts""3.2.0"
  }

Need to create "customjquery.js" file, file name you can create as you wish. Important, code that import dollar sign as " import $ from 'jquery' "

import $ from 'jquery' 
$(document).ready(function(){
    $(".clickClass").click(function(){
      $('.contentBox').hide()
    })
     $("p").click(function(){
        $(this).hide();
      });
  });

And go to the app.js file or go to the other pages where you need jquery code then call component.
import React from 'react';
import './App.css';
import 'jquery/dist/jquery.min.js'
import './customjquery'

function App() {
  return (
    <div className="App">
      <p>If you click on me, I will disappear.</p>
      <p>Click me away!</p>
      <p>Click me too!</p>
      <div className="clickClass">Click for the hide</div>
      <div className="contentBox">I will disappear when click .</div>
    </div>
  );
}
export default App;

Then run your project with this command : F:\react\cusotmjquery>npm start
Now your server will be run and you will find the result as below screenshot.

No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.