search

Home  >  Q&A  >  body text

Trigger mouse enter and leave events simultaneously

<p><br /></p> <pre class="brush:php;toolbar:false;"><Drawer anchor="left" className="drawerArea left-navigate" variant="permanent" open={true} PaperProps={{ style: { width: "inherit", background: "#172B4D", backgroundImage: `linear-gradient(to right,#172B4D 60% , white 40%)`, border: "none", overflowY: "hidden", }, }} > <Box> <Box> <Box> <Box className="listing" sx={{ width: "100%" }}> <List className="mp-0 wh-100 overflow-overlay"> {menus && menus.length > 0 && menus.map((item, index) => ( <Box key={index}> <ListItem ref={popoverAnchor} className={`mp-0 navigationList flex-start-center`} ** onMouseEnter={(e) => { setNestedArr([...item?.children]); popoverEnter(e); setAnchorEl(e?.currentTarget); }} onMouseLeave={(e) => { popoverLeave(e); }}** onClick={(e) => { console.log(item,'parent_clicked') }} > <ListItemText> <Box> {micons[item?.name] ? ( micons[item?.name] ) : ( <Icon>{item?.icon_class}</Icon> )} </Box> <Typography> {item?.name} </Typography> </Typography> } /> </ListItem> </Box> ))} </List> </Box> </Box> </Box> {open && nestedArr.length ? ( <NestedMenu open={open} setOpen={(val) => setOpen(val)} anchorEl={anchorEl} nestedArr={nestedArr}lightBackground={lightBackground} secondaryColor={secondaryColor} popoverAnchor={popoverAnchor} popoverEnter={popoverEnter} popoverLeave={popoverLeave} /> ) : null} </Box> </Drawer></pre> <p><strong> There are some menus on the left side of the page (using MUI library and material-ui-nested-menu-item library), when the mouse is hovered over the Listitems, it will show a menu with nested or sub menu and close the menu on mouse leave, but the problem I'm facing is that the onMouseLeave event is fired at the same time while hovering over the menu, so the menu doesn't open. I can't figure out what the problem is. </strong></p>
P粉018548441P粉018548441470 days ago488

reply all(1)I'll reply

  • P粉366946380

    P粉3669463802023-08-14 00:16:12

    The problem you describe is common when handling nested elements and mouse events in React. When you have nested elements and attach onMouseEnter and onMouseLeave events to the parent element, moving the mouse over the child element will trigger the parent element's onMouseLeave event even if the mouse is still within the range of the parent element. This is because the mouse has "left" the parent element and "entered" the child element.

    To solve this problem, you can use onMouseOver and onMouseOut events instead of onMouseEnter and onMouseLeave. The onMouseOver and onMouseOut events don't bubble up the same way, so they can help avoid this problem.

    reply
    0
  • Cancelreply