Created
January 7, 2024 07:29
-
-
Save GalindoSVQ/d807f608400fdb2375470944fe5783a1 to your computer and use it in GitHub Desktop.
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 * as React from 'react'; | |
| React.useEffectEvent = React.experimental_useEffectEvent; | |
| export function useClickAway(callback) { | |
| const ref = React.useRef(null); | |
| const onEventHandler = React.useEffectEvent((e) => { | |
| const element = ref.current; | |
| if (element && !element.contains(e.target)) { | |
| callback(e); | |
| } | |
| }); | |
| React.useEffect(() => { | |
| document.addEventListener('mousedown', onEventHandler); | |
| document.addEventListener('touchstart', onEventHandler); | |
| return () => { | |
| document.removeEventListener('mousedown', onEventHandler); | |
| document.removeEventListener('touchstart', onEventHandler); | |
| }; | |
| }, []); | |
| return ref; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackblitz.com/edit/stackblitz-starters-axu6qg?file=src%2FApp.tsx