Created
September 12, 2019 15:01
-
-
Save MariaSzubski/31e7c16681f01c3c9754d2691b2e7d73 to your computer and use it in GitHub Desktop.
React Hook - toggle Menu with outside click
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 ToggleMenu = props => { | |
| const [isOpen, setOpen] = useState(false) | |
| const toggleNav = () => setOpen(!isOpen) | |
| const nodeRef = useRef() | |
| useEffect(() => { | |
| const handleOutsideClick = e => { | |
| if (!nodeRef.current.contains(e.target)) { | |
| toggleNav() | |
| } | |
| } | |
| if (isOpen) { | |
| document.addEventListener("mousedown", handleOutsideClick) | |
| } | |
| return () => { | |
| document.removeEventListener("mousedown", handleOutsideClick) | |
| } | |
| }, [isOpen]) | |
| return ( | |
| <div ref={nodeRef}> | |
| <NavBtn | |
| onClick={toggleNav} | |
| role="button" | |
| aria-expanded={isOpen ? true : false} | |
| aria-label={`Toggle Navigation Menu`} | |
| tabindex="0" | |
| > | |
| <span tabIndex="-1"> | |
| <SVG src={icon} aria-label={`Navigation Menu Button`} /> | |
| </span> | |
| </NavBtn> | |
| <NavLinks nav={props.nav} isOpen={isOpen} /> | |
| </div> | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment