Skip to content

Instantly share code, notes, and snippets.

@akinncar
Last active March 17, 2021 22:28
Show Gist options
  • Save akinncar/9686973b60922260a21e1fb5e334ecf5 to your computer and use it in GitHub Desktop.
Save akinncar/9686973b60922260a21e1fb5e334ecf5 to your computer and use it in GitHub Desktop.
Hook to catch click outside modal
import { useEffect, RefObject } from 'react';
export function useOutsideClick(ref: RefObject<HTMLInputElement>, callback) {
function handleClick(e: MouseEvent) {
if (ref.current === e.target) {
callback();
}
}
useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment