Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Created June 24, 2019 05:34
Show Gist options
  • Save nicksheffield/444f797abf59e906a3fc3ca6b03ad2fb to your computer and use it in GitHub Desktop.
Save nicksheffield/444f797abf59e906a3fc3ca6b03ad2fb to your computer and use it in GitHub Desktop.
Handle clicks outside of an element. Useful for elements that display overlays like datepickers.
import { useEffect } from 'react'
const getPath = function(event) {
const path = []
let currentElem = event.target
while (currentElem) {
path.push(currentElem)
currentElem = currentElem.parentElement
}
if (path.indexOf(window) === -1 && path.indexOf(document) === -1) path.push(document)
if (path.indexOf(window) === -1) path.push(window)
return path
}
const useOutsideClick = (ref, cb) => {
useEffect(() => {
const handleClickOutside = (e) => {
if (getPath(e).indexOf(ref.current) === -1) {
cb()
}
}
document.body.addEventListener('mousedown', handleClickOutside)
return () => document.body.removeEventListener('mousedown', handleClickOutside)
}, [ref.current])
}
export default useOutsideClick
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment