简体   繁体   中英

React, click outside event happens right after click to open, preventing the modal from showing

On button click I want the Modal to appear. The Modal component adds a eventListener so it closes when you click outside the modal. In React 18 the click event triggers because the button click that happend before Modal was rendered? If I change to react 17 this does not happen.

Find a CodeSandbox here . Notice, when you click the button the show state sets to true. Then the Modal component renders and calls the close function directly.

App.js:

import { useState } from "react";
import Modal from "./Modal";
import "./styles.css";

export default function App() {
  const [show, setShow] = useState(false);

  const close = () => {
    setShow(false);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button
        onClick={(e) => {
          setShow(true);
        }}
      >
        Click
      </button>
      {show && <Modal close={close} />}
    </div>
  );
}

Modal.js

import "./styles.css";
import { useRef, useEffect } from "react";

export default function Modal({ close }) {
  const ref = useRef(null);

  useEffect(() => {
    const handleOutsideClick = (e) => {
      if (!ref?.current?.contains(e.target)) {
        console.log("This one gets called because of the button click", e);
        close();
      }
    };

    document.addEventListener("click", handleOutsideClick, false);
    return () => {
      document.removeEventListener("click", handleOutsideClick, false);
    };
  }, [close]);

  return (
    <div ref={ref} className="Modal">
      <h1>I'm a Modal!</h1>
    </div>
  );
}

You can call event.stopPropagation to prevent multiple click handlers capturing the same click event.

    onClick={(e) => {
      e.stopPropagation();
      setShow(true);
    }}

I don't know why this would differ between React 17 and 18. React uses its own "synthetic events", and there might have been a change in how event propagation/bubbling happens between the two versions.

It might be connected to what's called "automatic batching" in React 18. https://github.com/reactwg/react-18/discussions/21

In your example, the Modal component uses native event handling with document.addEventlistener() . It seems that React 18 handles the click inside the app, which triggers a state change and a rerender, mounts the Modal component, runs the useEffect() hook, and creates the new event listener before the click event is propagated to the window node. In React 17, the event presumably finishes propagating before the re-render happens.

You could change your if statement in handleOutsideClick as below. Yours is not working because the button for opening the Modal , since it's not inside the Modal , passes this if(!ref?.current?.contains(e.target)) you have.

Here is a working fork of your CodeSandbox. I'm passing the button's ref to Modal . And here is what I changed:

const handleOutsideClick = (e) => {
  if (!ref?.current?.contains(e.target) && !openButtonRef?.current?.contains(e.target)) {
    console.log("This one gets called because of the button click", e);
    close();
  }
};

A different solution to the problem involves new startTransition API: https://codesandbox.io/s/gracious-benz-0ey6ol?file=/src/App.js:340-388

onClick={(e) => {
  startTransition(() => {
    setShow(true);
  })
}}

This new API ( doc ) definitely helps, but I'm not sure this is a legit solution, and docs are not quite clear on that. Would be nice if someone from React can comment -- is this an abuse?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM