Home  >  Article  >  Web Front-end  >  How to implement closing event in react modal

How to implement closing event in react modal

藏色散人
藏色散人Original
2022-12-20 11:04:392555browse

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);
      }
    });
  }, []);```
const messageRef = useRef(null);

```

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!

Statement:
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