Skip to content

Instantly share code, notes, and snippets.

@MariaSzubski
Created September 12, 2019 15:01
Show Gist options
  • Select an option

  • Save MariaSzubski/31e7c16681f01c3c9754d2691b2e7d73 to your computer and use it in GitHub Desktop.

Select an option

Save MariaSzubski/31e7c16681f01c3c9754d2691b2e7d73 to your computer and use it in GitHub Desktop.
React Hook - toggle Menu with outside click
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