Benny
Benny

Reputation: 857

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>
  );
}

Upvotes: 8

Views: 7676

Answers (4)

Spyros Argalias
Spyros Argalias

Reputation: 156

Dan Abramov gives some suggestions in this comment (https://github.com/facebook/react/issues/24657#issuecomment-1150119055).

Suggestion 1 is: In the useEffect, delay the addEventListener call with a setTimeout with 0 wait time. Example:

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

    const timeoutId = setTimeout(() => {
      document.addEventListener("click", handleOutsideClick, false);
    }, 0);
    return () => {
      clearTimeout(timeoutId);
      document.removeEventListener("click", handleOutsideClick, false);
    };
  });

Suggestion 2 is to capture the current event and ignore just that one in the modal's useEffect. Example provided by @YoussoufOumar in this answer and at https://github.com/microsoft/fluentui/pull/18323

Upvotes: 3

Youssouf Oumar
Youssouf Oumar

Reputation: 46191

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();
  }
};

Upvotes: -1

pavek
pavek

Reputation: 307

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?

Upvotes: -1

H&#229;ken Lid
H&#229;ken Lid

Reputation: 23074

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.

Upvotes: 8

Related Questions