Skip to content

Instantly share code, notes, and snippets.

@akinncar
Created June 7, 2021 19:49
Show Gist options
  • Save akinncar/1c39bea08b5e2c4cef551d4d2abb3f46 to your computer and use it in GitHub Desktop.
Save akinncar/1c39bea08b5e2c4cef551d4d2abb3f46 to your computer and use it in GitHub Desktop.
useClickOutside v2
useClickOutside({
isOpen,
ref: containerRef,
onRequestClose: () => setIsOpen(false),
})
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