Last active
October 1, 2022 03:40
-
-
Save Phryxia/2b3f884345261fbd19b95505ced8eabc to your computer and use it in GitHub Desktop.
Simple react hook implementation for detecting click of outside of the given DOM
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, useRef } from 'react' | |
export function useOutsideClickHandler<T extends HTMLElement>( | |
callback: (e: MouseEvent) => void | |
) { | |
const ref = useRef<T>(null) | |
useEffect(() => { | |
function handleClick(e: MouseEvent): void { | |
if (!ref.current?.contains(e.target as Node)) { | |
callback(e) | |
} | |
} | |
document.addEventListener('click', handleClick) | |
return () => document.removeEventListener('click', handleClick) | |
}, [callback]) | |
return ref | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example