Created
October 7, 2022 19:21
-
-
Save finom/55b7af1a5ab6504b3ac98b1ce9e88152 to your computer and use it in GitHub Desktop.
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'; | |
/** | |
* | |
* @example | |
* const ref = useClickOutside<HTMLDivElement>((evt: MouseEvent) => console.log('blah')) | |
* <div ref={ref} /> | |
*/ | |
type ClickEvent = MouseEvent & { target: HTMLElement }; | |
export default function useClickOutside<T extends HTMLElement>( | |
callback: (evt: ClickEvent) => void, | |
) { | |
const ref = useRef<T>(null); | |
useEffect(() => { | |
function handler(evt: MouseEvent) { | |
const { target } = evt; | |
if (ref.current && target && !ref.current.contains(target as HTMLElement)) { | |
callback(evt as ClickEvent); | |
} | |
} | |
// Bind the event listener | |
document.addEventListener('click', handler); | |
return () => { | |
// Unbind the event listener on clean up | |
document.removeEventListener('click', handler); | |
}; | |
}, [callback, ref]); | |
return ref; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment