negomi/react-burger-menu

Menu not closing when using Link

Closed this issue · 1 comments

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.

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 😄