Created
June 7, 2021 19:49
-
-
Save akinncar/1c39bea08b5e2c4cef551d4d2abb3f46 to your computer and use it in GitHub Desktop.
useClickOutside v2
This file contains hidden or 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
useClickOutside({ | |
isOpen, | |
ref: containerRef, | |
onRequestClose: () => setIsOpen(false), | |
}) |
This file contains hidden or 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, RefObject } from 'react' | |
type UseClickOutsideProps = { | |
ref: RefObject<HTMLElement> | |
onRequestClose: () => void | |
isOpen: boolean | |
} | |
export const useClickOutside = ({ | |
ref, | |
isOpen, | |
onRequestClose, | |
}: UseClickOutsideProps): void => { | |
useEffect(() => { | |
function handleClickOutside(event: MouseEvent) { | |
if (isOpen) { | |
if (ref.current && !ref.current.contains(event.target as Node)) { | |
onRequestClose() | |
} | |
} | |
} | |
document.addEventListener('mousedown', handleClickOutside) | |
return () => { | |
document.removeEventListener('mousedown', handleClickOutside) | |
} | |
}, [ref, isOpen, onRequestClose]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment