skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    I edited the file: <Navbar isMenuOpen={isMenuOpen}> navbar opens/closes when the variable is set to true/false

    const togleMenu = () => {
    setIsMenuOpen(!isMenuOpen);
    console.log(isMenuOpen);
    
    };
    
    
    ...
    
    <NavbarMenuToggle
          aria-label={isMenuOpen ? "Close menu" : "Open menu"}
          className="sm:hidden"
          onClick={() => togleMenu()} // clicking on menu icon would change the value
        />
    
    ...
    
    <NavbarMenuItem key={`${item}-${index}`}>
                <Link
                  color="foreground"
                  className="w-full"
                  href={"#" + item.path}
                  size="lg"
                  onPress={() => togleMenu()} // change the value
                >
                  {item.name}
                </Link>
    

  2. Can you provide more code?

    I can give you example how it should look:

    import React from 'react';
    
    export function App(props) {
      const [isMenuOpen, setIsMenuOpen] = React.useState(false);
    
      return (
         <div>
         <div
             onClick={() => {
             setIsMenuOpen(!isMenuOpen)
             console.log(isMenuOpen);}}
         >PRESS</div>
    </div>
      )
    }
    

    Maybe you put useState hook at the wrong place?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search