Skip to content

Instantly share code, notes, and snippets.

@KacperKozak
Created February 15, 2022 16:54
Show Gist options
  • Save KacperKozak/bc726c23896608158e67f76a0da39c63 to your computer and use it in GitHub Desktop.
Save KacperKozak/bc726c23896608158e67f76a0da39c63 to your computer and use it in GitHub Desktop.
React useOnClickOutside hook
import { MutableRefObject, useEffect } from 'react'
export const useOnClickOutside = (refs: MutableRefObject<any>[], handler: () => void) => {
useEffect(() => {
const listener = (event: any) => {
const someElContainsTarget = refs.some((ref) =>
ref.current?.contains(event.target),
)
if (!someElContainsTarget) handler()
}
document.addEventListener('mousedown', listener)
document.addEventListener('touchstart', listener)
return () => {
document.removeEventListener('mousedown', listener)
document.removeEventListener('touchstart', listener)
}
}, [...refs, handler])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment