Skip to content

Instantly share code, notes, and snippets.

@SimpleCookie
Created April 21, 2020 08:57
Show Gist options
  • Save SimpleCookie/0375de734a241b951459e13dbce23eac to your computer and use it in GitHub Desktop.
Save SimpleCookie/0375de734a241b951459e13dbce23eac to your computer and use it in GitHub Desktop.
useRelativeClick React Hook
import { useEffect } from "react";
export function useRelativeClick(ref, callback: (inside: boolean) => any) {
function handleClickOutside(event) {
if (ref.current) {
const insideClick = ref.current.contains(event.target)
callback(insideClick)
}
}
useEffect(() => {
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
// tslint:disable-next-line: align
}, [ref]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment