I use focus-trap-react to trap element focus inside of popup window. I would like to be able to close the window when user clicks outside of the popup window. I cannot find the way how to accomplish this.
I tried the following approach but the click events outside of popup are never detected:
const Popup = () =>{
const popupRef = useRef();
const onClick = ev =>{
if (!popupRef.current.contains(ev.target)) console.log('clicked outside')
}
useEffect(()=>{
window.addEventListener('click', onClick);
return (()=>{
window.removeEventListener('click', onClick);
})
}, []);
return (
<FocusTrap>
<div id="modal-dialog" className="modal" ref={popupRef}>
<button>Ok</button>
<button>Cancel</button>
</div>
</FocusTrap>)
}