Search code examples
reactjstypescriptnext.jsreact-hooksnextui

Next UI navbar menu won't close after selecting an item


The navbar menu component won't close when the option from the menu was selected.

The menu successfully opens and closes within the menu icon. I tried to to use onPress() but it doesn't seem to help a lot

"use client"
...
export default function Header() {
  const [isMenuOpen, setIsMenuOpen] = React.useState(false);
return(
...
<NavbarMenu>
        {menuItems.map((item, index) => (
          <NavbarMenuItem key={`${item}-${index}`}>
            <Link
              color="foreground"
              className="w-full"
              href={"#" + item.path}
              size="lg"
              onPress={() => {
                **console.log("closing")**; //Message appears
                **setIsMenuOpen(!isMenuOpen)**; //Menu won't close
              }}
            >
              {item.name}
            </Link>
          </NavbarMenuItem>
        ))}
</NavbarMenu>
)

UPD: when I remove const [isMenuOpen, setIsMenuOpen] = React.useState(false); the menu still opens/closes! It seems that there is a NavbarMenuToggle which has an onChange event which controls menu's behavior

https://nextui.org/docs/components/navbar#navbarmenutoggle-events

How to access this handler?


Solution

  • You need to control the menu directly with the "NavBar" component, which takes the following props:

    • isMenuOpen
    • onMenuOpenChange

    These two props will allow you to control the toggle.

    export default function Header() {
      const [isMenuOpen, setIsMenuOpen] = React.useReducer((current) => !current, false);
    
      return(
        // You need to control your toggle menu directly with the Navbar component.
        <Navbar isMenuOpen={isMenuOpen} onMenuOpenChange={setIsMenuOpen}>
          <NavbarMenu>
            {menuItems.map((item, index) => (
              <NavbarMenuItem key={`${item}-${index}`}>
                <Link
                  color="foreground"
                  className="w-full"
                  href={"#" + item.path}
                  size="lg"
                  onPress={() => setIsMenuOpen()}
                >
                  {item.name}
                </Link>
              </NavbarMenuItem>
            ))}
          </NavbarMenu>
        </Navbar>
      )