Last active
March 17, 2021 22:28
-
-
Save akinncar/9686973b60922260a21e1fb5e334ecf5 to your computer and use it in GitHub Desktop.
Hook to catch click outside modal
This file contains hidden or 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, 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