Created
February 13, 2021 14:35
-
-
Save osmanmesutozcan/591ad67fcf6cde80be7db213523e8fab to your computer and use it in GitHub Desktop.
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
/** | |
* Register a callback to trigger when we detect a click outside of refs. | |
*/ | |
export function useDetectClickOutside(refs, callback) { | |
useEffect(() => { | |
const handleMouseDown = (e) => { | |
const clickOutsideOfRefs = | |
refs.every((r) => r.current) && | |
refs.every((r) => !r.current.contains(e.target)); | |
if (clickOutsideOfRefs) { | |
callback(); | |
} | |
}; | |
document.addEventListener("mousedown", handleMouseDown); | |
return () => document.removeEventListener("mousedown", handleMouseDown); | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment