0

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>)
}
okram
  • 810
  • 3
  • 11
  • 17
  • Does this answer your question? [Detect click outside React component](https://stackoverflow.com/questions/32553158/detect-click-outside-react-component) – DBS Sep 09 '21 at 16:07
  • no because none of the answers there uses react-focus-trap as part of its solution and this questions has the usage of react-focus-trap in its center – okram Sep 09 '21 at 21:04
  • Looking at the [documentation](https://github.com/focus-trap/focus-trap#createoptions), the library seems to have an `allowOutsideClick` option that would let you use the above solution. – DBS Sep 10 '21 at 08:37
  • Great, I did not read the options part well enough... Should this qualify as an answer? – okram Sep 11 '21 at 09:07

0 Answers0