From the UX's experience, a popup modal should be closed in two ways, one way is from the build in close button, another way is close the modal from everywhere of the web page. Here I am going to share how to achieve this second method.
A easy choice is to use the react modal, react modal provide the completed solution for developers to build a modal, includes its overlay, its modal styles, open and close functionalities. If you are interested, check this out: https://reactcommunity.org/react-modal/ . The onRequestClose
can easy handle the modal to be closed from outside of the modal itself.
Here is the way to build the close handler from your own:
//Implement it by define your ref and complete your close modal function
function closeModalOutside(ref, handler) {
useEffect(() => {
const listener = event => {
//Make sure the handler does nothing when it's in current ref and its decendant
if(!ref.current || ref.current.contains(event.target)) {
return;
}
handler();
}
document.addEventListener('mousedown', listener);
return () => {
document.removeEventListener('mousedown', listener);
}
},[])
}
Add an event listener while the modal is open is the important logic here.
For example to understand it better, check here: https://codesandbox.io/s/hooks-modal-j2q4k?file=/src/modal.js:1874-1879