How to close my menu after clicking on a menu item in react?

Viewed 1272

So right now I have a hamburger menu icon that opens up the mobile menu whenever I click on the icon. The menu covers my entire mobile screen, so whenever I click on "Home" or "About us" it doesn't close. How can I write the logic to close the menu when I click on a menu item?

Here is the code that opens the menu when I click it

<ul className={click ? 'nav-menu active' : 'nav-menu'}>

My issue is whenever I click on my menu items inside of the ul, I can't get rid of the menu. I tried to do the reverse and set the <li> tag to be click ? 'nav-menu' : 'nav-menu active' but all that did was delete the menu items from showing up and was causing issues.

<ul className={click ? 'nav-menu active' : 'nav-menu'}>
    <li className={}>
      <Link to='/' className='nav-links'>
        Home
      </Link>
    </li>
</ul>

This is the CSS to make the menu open up when I click it

.nav-menu {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 500px;
    position: absolute;
    top: 80px;
    left: -100%;
    opacity: 1;
    transition: all 0.5s ease;
}

.nav-menu.active {
    background: #6668f4;
    left: 0;
    opacity: 1;
    transition: all 0.5s ease;
    z-index: 1;
}

I just need the logic to make this li tag to close the entire ul menu when I click on "Home"

<li className={}>
  <Link to='/' className='nav-links'>
    Home
  </Link>
</li>

Or let me know if that is not the proper way to do it and if there's a different approach

1 Answers

Can't you just set an onClick for your li items and set click to false in them? or just use a javascript regular function to open and close the menu like this:

const menuToggle = () => {
    let nav = document.getElementsByClassName("nav-menu")
    if(nav[0].classList.contains("active")){
        nav[0].classList.remove("active")
    } else {
        nav[0].classList.add("active")
    }
}

and then give it to your menu:

<ul className='nav-menu' onClick={menuToggle}>
    <li className={}>
      <Link to='/' className='nav-links'>
        Home
      </Link>
    </li>
</ul>

========================

also you can do this to set click to false if you have it defined as a state:

const [click, seClick] = useState(false)

<ul 
  className={click ? 'nav-menu active' : 'nav-menu'} 
  onClick={() => setClick(prevState => !prevState)}>
    <li>
      <Link to='/' className='nav-links'>
        Home
      </Link>
    </li>
</ul>
Related