Last active
February 21, 2022 11:48
-
-
Save mzahor/8deb94e7976da1aa62478c202795a1a9 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
import { useCallback, useEffect } from 'react'; | |
export function useClickOutside(isOpen, ref, onClose) { | |
const handleOutsideClick = useCallback( | |
(e) => { | |
if (!isOpen) return; | |
const path = e.path || (e.composedPath && e.composedPath()); | |
if (!path.includes(ref.current)) { | |
onClose(); | |
} | |
}, | |
[isOpen, onClose, ref] | |
); | |
useEffect(() => { | |
document.body.addEventListener('click', handleOutsideClick); | |
return () => { | |
document.body.removeEventListener('click', handleOutsideClick); | |
}; | |
}, [handleOutsideClick, isOpen]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment