React – extend events to include children

I’m very new to react and I’m having trouble extending an mouse leave event to a rendered sub-menu.

currently the mouse hovers over navbar item and sub-menu renders. mouse leaves navigation bar item to select item from submenu. submenu disappears. I would like the submenu to stay open while the mouse is over the nav item AND within the sub-menu. I’ve tried multiple different things at this point, but I’m struggling to understand how to make some conditional logic that will work.

Here is the function that renders the child.

function NavItem(props) {
  const [open, setOpen] = useState(false)
  return (
    <li className='nav-item'>
      <p1 className='icon-button' onMouseEnter={() => setOpen(!open)} onMouseLeave={() => setOpen(false)}>
        {props.name}
      </p1>
      {open && props.children}    
    </li> 
  )
}

this is the child function.

function PlatformMenu() {
  return (
    <div className='dropdown' >
      <li>
        <ul className='dropdown-item' ><a href='#'>Sub-Menu Item</a></ul>
      </li>
    </div>
  )
}

>Solution :

put submenu inside your p1, like this for example:

 <li className='nav-item'>
      <p1 className='icon-button' onMouseEnter={() => setOpen(!open)} 
           onMouseLeave={() => setOpen(false)}>
        {props.name}
        {open && props.children}    
      </p1>
    </li> 

p.s.:
I will join the answer in the comments, I would not advise you to use the state for this task, it is better to use CSS styles for this.

Leave a Reply