How to integrate a React application with jQuery

React is a popular JavaScript framework/library used by front-end developers to build web applications. When used as a framework, React takes over the entire application and defines how the application is built. But when used as a library, it's only employed for use in some parts of the application, and it doesn't entirely define how it is built. In this answer, React would be treated as a framework.

On the other hand, jQuery is one of the most popular javascript libraries. It's a simplified yet powerful way of carrying out javascript tasks on your website.

Why use jQuery with React

For some people, especially beginners who are just learning to use React and previously used jQuery for tasks like DOM manipulation and Ajax calls, it can be tempting to continue to want to employ jQuery to perform these actions in React. However, this is considered bad practice and can be avoided in most cases. This is because React uses what is called a virtual DOM and has full control over it. Manipulating the real DOM—manipulating the DOM outside React using jQuery in this instance—creates a kind of discord between React's virtual DOM and the real DOM (which is what React has access to).

However, if the need arises to employ jQuery in a React application, it can still be implemented without causing any conflict. In this Answer, we will go over how jQuery can safely be used with React.

Safely integrating jQuery into a React application

To safely use jQuery in a React application, we simply stop React from managing the DOM and instead use jQuery. This means that the DOM is now handled solely by one entity, and therefore, no conflict would arise.

This is done by writing our jQuery commands in the componentDidMount lifecycle hook.

Lifecycle hooks are basically methods/functions that run at critical points in the life of an application, such as when the application is created, when it's mounted, when it's unmounted, when it's destroyed, and so on.

Requirements

React: To create one, run npx create-react-app app-name in a console and follow the prompt.

jQuery: Install jQuery using npm install jquery if it's not already installed.

Example

In this example, we'll use jQuery to change the height of a div element when a button is clicked.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Explanation

  • Line 4: We import $ provided to us by jQuery to select DOM elements.

  • Line 8: We define the function that will run immediately after the application is mounted, which would house our jQuery code.

  • Line 10: We select the button element using its className and added a click event listener to it.

  • Line 13: Once the button is clicked, we then select the div element and change its height using jQuery CSS API.

Free Resources