Skip to content

Instantly share code, notes, and snippets.

@finom
Created October 7, 2022 19:21
Show Gist options
  • Save finom/55b7af1a5ab6504b3ac98b1ce9e88152 to your computer and use it in GitHub Desktop.
Save finom/55b7af1a5ab6504b3ac98b1ce9e88152 to your computer and use it in GitHub Desktop.
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