Created
June 24, 2019 05:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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