Last active
August 29, 2019 09:42
-
-
Save n1ru4l/ed2ee627022ab7d8e3ebc3c92814d9d5 to your computer and use it in GitHub Desktop.
React onClickOutside hook
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
| const MyComponent = () => { | |
| const ref = useOnClickOutside(() => alert("sup")); | |
| return <div ref={ref}>Shoop</div>; | |
| } |
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
| 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