negomi / react-burger-menu

:hamburger: An off-canvas sidebar component with a collection of effects and styles using CSS transitions and SVG path animations
http://negomi.github.io/react-burger-menu/
MIT License
5.05k stars 586 forks source link

Menu not closing when using Link #446

Closed ReginaldJbeili closed 3 years ago

ReginaldJbeili commented 3 years ago

Hi,

I just recently changed my burger to use Links instead of 'a' tags and I had to use the isOpen prop for handling the menu but as seen on the code below, adding an onClick setShowMenu to the Link doesn't trigger the menu to close. It was working without needing state management when I used 'a' tags.

const Burger = () => {
  const [showMenu, setShowMenu] = useState(false)
    return (
        <Menu right isOpen={showMenu}>
          <Link className="menu-item" to="/" onClick={()=>setShowMenu(false)}><AiFillHome size="2rem" style= 
             {{marginRight: "1rem"}}/><span className="link-text">Home</span></Link>
          <Link className="menu-item" to="/support"  onClick={()=>setShowMenu(false)}><TiInfoLarge size="2rem" style= 
             {{marginRight: "1rem"}}/><span className="link-text">Support</span></Link>
          <Link className="menu-item" to="/partners" onClick={()=>setShowMenu(false)}><FaHandshake size="2rem" 
              style={{marginRight: "1rem"}}/><span className="link-text">Partners</span></Link>
      </Menu>
    )
}

I've not seen examples of hooks being used in the burger, wondering if this is an issue.

negomi commented 3 years ago

Hi @ReginaldJbeili,

The piece you're missing is the onStateChange prop. You need to use that to keep your own state in sync whenever the menu opens/closes.

What's happening currently is that when you open the menu for the first time, your own showMenu variable is still false, so when you click one of your links, nothing happens because your click handler just tries to set it to false again.

There's an example of how it all works together here: https://github.com/negomi/react-burger-menu/wiki/FAQ#i-want-to-control-the-open-state-programmatically-but-i-dont-understand-how-to-use-the-isopen-prop

Hope that helps 😄