Home > Software engineering >  React - extend events to include children
React - extend events to include children

Time:12-24

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' onm ouseEnter={() => setOpen(!open)} onm ouseLeave={() => 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>
  )
}

CodePudding user response:

put submenu inside your p1, like this for example:

 <li className='nav-item'>
      <p1 className='icon-button' onm ouseEnter={() => setOpen(!open)} 
           onm ouseLeave={() => 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.

  • Related