S
S
Sergey2021-01-20 17:04:54
React
Sergey, 2021-01-20 17:04:54

How to close a popup window in react?

Good afternoon. The application has the ability to edit menu items. Each item has a button, which, when clicked, will display a pop-up menu. I plan to implement this using css classes. How to implement the collapse of this element when clicking on any other area?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-01-20
@Banjamin

Watch for clicks outside the root node :

function Modal(props) {
  const root = useRef();

  useEffect(() => {
    const onClick = e => root.current.contains(e.target) || закрытьОкно();
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  return (
    <div ref={root}>
      ...
    </div>
  );
}

Or make the root node span the entire page and track clicks on it :
function Modal(props) {
  return (
    <div
      className="modal-overlay"
      onClick={e => (e.currentTarget === e.target) && закрытьОкно()}
    >
      ...
    </div>
  );
}

.modal-overlay {
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
}

A
Anton, 2021-01-20
@karminski

Good afternoon. You need something like this
https://www.npmjs.com/package/react-onclickoutside

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question