Created
April 21, 2020 08:57
-
-
Save SimpleCookie/0375de734a241b951459e13dbce23eac to your computer and use it in GitHub Desktop.
useRelativeClick React Hook
This file contains 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"; | |
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