Home > Web Front-end > Front-end Q&A > How to implement closing event in react modal

How to implement closing event in react modal

藏色散人
Release: 2022-12-20 11:04:39
Original
2598 people have browsed it

React modal method to implement closing events: 1. Listen to the target of the browser onclick event; 2. Determine the click through the "if (e.target != messageRef.current) {setMessageCode(false);}" statement Event, if it is not a modal box, just execute the closing event.

How to implement closing event in react modal

#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.

How to implement closing event in react modal?

reactClick somewhere else to close the Modal box

Principle: Very simple, it is to listen to the target of the browser onclick event, determine the click event, and execute the closing event if it is not a modal box.

Server-side rendering cannot get the window object in useEffect

useLayoutEffect(() => {
    window.addEventListener("click", (e) => {
      if (e.target != messageRef.current) {
        setMessageCode(false);
      }
    });
  }, []);```
Copy after login
const messageRef = useRef(null);
Copy after login

```

The function signature of useLayoutEffect is the same as useEffect, but it will be synchronized after all DOM changes Call effect. You can use this to read the DOM layout and trigger re-rendering synchronously. Before the browser performs drawing, the update plan inside useLayoutEffect will be refreshed synchronously.

Recommended learning: "react video tutorial"

The above is the detailed content of How to implement closing event in react modal. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template