Created
August 10, 2021 07:05
-
-
Save tkim90/fd1eb87f07758e83cc24775300eb0d20 to your computer and use it in GitHub Desktop.
useOnClickOutside 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
| import * as React from "react"; | |
| export default function useOnClickOutside(ref, handler) { | |
| React.useEffect( | |
| () => { | |
| const listener = (event) => { | |
| // Do nothing if clicking ref's element or descendent elements | |
| if (!ref.current || ref.current.contains(event.target)) { | |
| return; | |
| } | |
| handler(event); | |
| }; | |
| document.addEventListener("mousedown", listener); | |
| document.addEventListener("touchstart", listener); | |
| return () => { | |
| document.removeEventListener("mousedown", listener); | |
| document.removeEventListener("touchstart", listener); | |
| }; | |
| }, | |
| // Add ref and handler to effect dependencies | |
| // It's worth noting that because passed in handler is a new ... | |
| // ... function on every render that will cause this effect ... | |
| // ... callback/cleanup to run every render. It's not a big deal ... | |
| // ... but to optimize you can wrap handler in useCallback before ... | |
| // ... passing it into this hook. | |
| [ref, handler] | |
| ); | |
| } | |
| // Usage: | |
| const [menuOpen, setMenuOpen] = React.useState(false); | |
| useOnClickOutside(list, () => setMenuOpen(false)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment