React JS: jQuery is not working after React upgraded from version 16.13.1 to 18.2.0

49 views Asked by At

I'm upgrading the legacy code of a React app from version 16.13.1 to 18.2.0. The code currently utilizes jQuery. Before it's upgraded, the app works fine.

I found the issues in the index.js render.

React 16 uses this to render:

import { render } from 'react-dom';

const container = document.getElementById('app');
render(<App tab="home" />, container);

While according to react documentation, React 18 uses this:

import { createRoot } from 'react-dom/client';

const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App tab="home" />);

I can revert the previous syntax and the jQuery will work, but then it will give me a warning:

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead.
Until you switch to the new API, your app will behave as if it's running React 17.

What supposed to happen is, that when I click an expandable menu, e.g. Organization Unit, it will expand and show its children. The menu will collapse if clicked again.

When jQuery uses the first render() syntax, it works as intended: jQuery working

When using createRoot(), nothing happened even when I clicked the menu repeatedly: jQuery not working

Here is the jQuery code (legacy code, not mine), if needed:

$("#sidebar-menu a").on("click", function (e) {
      if ($(this).parent().hasClass("submenu")) {
        e.preventDefault();
      }
      if (!$(this).hasClass("subdrop")) {
        $("ul", $(this).parents("ul:first")).slideUp(350);
        $("a", $(this).parents("ul:first")).removeClass("subdrop");
        $(this).next("ul").slideDown(350);
        $(this).addClass("subdrop");
      } else if ($(this).hasClass("subdrop")) {
        $(this).removeClass("subdrop");
        $(this).next("ul").slideUp(350);
      }
    });

$("#sidebar-menu ul li.submenu a.active")
  .parents("li:last")
  .children("a:first")
  .addClass("active")
  .trigger("click")

Is there anything I missed? Please let me know if additional information or context is needed.

Note:

  • I know it's not the best practice to use jQuery in React due to both manipulating the DOM.
  • Removing the jQuery is not an option.
0

There are 0 answers