Created
December 3, 2021 01:23
-
-
Save vczb/15bd6cf1a0f8e7ba8c14b68f29ab8403 to your computer and use it in GitHub Desktop.
click away listener to react with typescript
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 } from 'react' | |
| type Props = { | |
| ref: React.RefObject<HTMLElement> | |
| handleClickAway: () => void | |
| } | |
| const useClickAwayListener = (ref: any, handleClickAway: any) => { | |
| const handleClick = (event: MouseEvent) => { | |
| if (!ref?.current?.contains(event?.target)) { | |
| handleClickAway() | |
| } | |
| } | |
| useEffect(() => { | |
| document.addEventListener('click', handleClick) | |
| return () => document.removeEventListener('click', handleClick) | |
| }, []) | |
| } | |
| export default useClickAwayListener |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.