DEV Community

Max Frolov
Max Frolov

Posted on

React click outside hook

In case your click outside logic sucks - grab & use this one:

const useClickOutside = (ref, handleClickOutside) => {
  React.useEffect(() => {
    const handleTargetClick = e => {
      if (ref.current && !ref.current?.contains(e.target)) {
        typeof handleClickOutside === "function" && handleClickOutside(e)
      }
    }

    document.addEventListener('mousedown', handleTargetClick, true)

    return () => {
      document.removeEventListener('mousedown', handleTargetClick, true)
    }
  })
}

Top comments (2)

Collapse
 
yizhuang profile image
yi

You forgot useCapture

Collapse
 
max_frolov_ profile image
Max Frolov

It makes sense. Thanks, I'll edit.