If you have to use JQuery in your React JS or Next Js application, you can either install the Jquery npm package or link to the Jquery CDN. However, using Jquery with React or Next is not a good practice and is not recommended.
It only takes three simple steps. This method packages Jquery with the React or Next production bundle. Therefore, the package size will increase.
If your Jquery import gives you the error
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
The second option is to link the Jquery CDN from your index.html file residing in the public folder. Note that this method will not bundle the Jquery dependency with the production bundle.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
The usage is similar to the previous example but without the
The simple answer is that Jquery performs direct DOM manipulations. That is against React Js principles, where React uses the virtual DOM to perform changes and ports only the necessary changes to the real DOM. Therefore, we do not access the DOM elements directly in React (except in useRef). That's a performance measure.