Skip to content

Instantly share code, notes, and snippets.

@n1ru4l
Last active August 29, 2019 09:42
Show Gist options
  • Save n1ru4l/ed2ee627022ab7d8e3ebc3c92814d9d5 to your computer and use it in GitHub Desktop.
Save n1ru4l/ed2ee627022ab7d8e3ebc3c92814d9d5 to your computer and use it in GitHub Desktop.
React onClickOutside hook
const MyComponent = () => {
const ref = useOnClickOutside(() => alert("sup"));
return <div ref={ref}>Shoop</div>;
}
export const useOnClickOutside = onClickOutside => {
const handlerRef = React.useRef(onClickOutside);
const elementRef = React.useRef(null);
if (onClickOutside !== handlerRef.current) {
handlerRef.current = onClickOutside;
}
useEffect(() => {
const handleClick = e => {
if (elementRef.current.contains(e.target)) {
return;
}
handlerRef.current(e);
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
return elementRef;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment