Home > References > Web Development > Reactjs references

How to use JQuery with React JS and Next JS

Last updated : July 10, 2022

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.

1. Installing the Jquery npm package

It only takes three simple steps. This method packages Jquery with the React or Next production bundle. Therefore, the package size will increase.

  1. Go to your project root, the same level where your package.json reside.
  2. Run npm install jquery --save, or yarn add jquery. That will add Jquery npm dependencies into your node_modules, and your package.json will reflect the package as "jquery": "^3.6.0". (your version may differ)
  3. Import Jquery import $ from "jquery" into pages where you want to use it.

If your Jquery import gives you the error "could not find a declaration file for module jquery", try to run npm i --save-dev @types/jquery to save it as a dev dependency.

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

2. Linking to Jquery CDN

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 import $ from "jquery" statement.

Why you shouldn't use Jquery with React Js?

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.

L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments