How to install and use jquery in react js?
April 14, 2023Hi Friends 👋,
Welcome To aGuideHub!
To install and use jquery in React js, you have to use the npm
or yarn
package manager that is how you can install the jquery
library into your project.
Today, I am going to show you, how to install and use jquery in react js.
install and use jquery
Install the following packages to use jquery
in react js.
npm
npm install jquery --save,
yarn
yarn add jquery
Table of contents
- Set up the React project.
- Import necessary components.
- Use jquery.
Step 1: Set up the React project.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import necessary components.
After installing jquery
, you have to import your React component. To do this, add the following line to the top of your component file.
import $ from "jquery"
import { useEffect } from "react";
Step 4: Use jquery.
In the function of jQuery, what is written in the value of the input field, it shows in the alert box.
<div>
<h1>This is a React App.</h1>
</div>
<div>
<input name="input" id="input" value="Jquery in React Js?"/>
</div>
React jquery example.
The code below is an example of this, The useEffect
hook is used to perform side effects in a functional
component, such as receiving data, setting event listeners, or in this case, showing an alert message.
App.js
import $ from "jquery"
import { useEffect } from "react";
export const App = () => {
useEffect(() => {
alert($("#input").val())
})
return(
<>
<div>
<h1>This is a React App.</h1>
</div>
<div>
<input name="input" id="input" value="Jquery in React Js?"/>
</div>
</>
)
}
export default App
Check the output of the above code example.
Here, we are provided code sandbox links for the above program install and use jquery in React js. Then you can use whenever you went and do the changes as per your requirements.
All the best 👍