Created
February 15, 2022 16:54
-
-
Save KacperKozak/bc726c23896608158e67f76a0da39c63 to your computer and use it in GitHub Desktop.
React useOnClickOutside hook
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 { 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