Created
June 12, 2021 07:43
-
-
Save ilxanlar/af01d9e8c9268f7ed1520310e7ca8350 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 { useEffect } from 'react' | |
export default function useOnClickOutside(ref, callback) { | |
useEffect(() => { | |
const listener = (event) => { | |
if (ref && ref.current && !ref.current.contains(event.target)) { | |
callback(event) | |
} | |
} | |
document.addEventListener('mousedown', listener) | |
document.addEventListener('touchstart', listener) | |
return () => { | |
document.removeEventListener('mousedown', listener) | |
document.removeEventListener('touchstart', listener) | |
} | |
}, [ref, callback]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment