Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created January 7, 2024 07:29
Show Gist options
  • Select an option

  • Save GalindoSVQ/d807f608400fdb2375470944fe5783a1 to your computer and use it in GitHub Desktop.

Select an option

Save GalindoSVQ/d807f608400fdb2375470944fe5783a1 to your computer and use it in GitHub Desktop.
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;
}
@GalindoSVQ

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment