简体   繁体   中英

close a submenu when another menu item is clicked

I researched and attempted to implement some of the solutions provided, but I was unsuccessful. I modified my dropdown menu and click so that each submenu opens and closes when its parent is clicked. I'd like to have an open submenu close when a different menu is clicked so that they aren't all stacked at the menu bar. Could someone please tell me how I can do this? Thank you for your assistance.

I am using next js.

 <div className={ classNames(classes.root, { [classes.rootActive]: active , [classes.rootExpanded]: isMenuShrunk, })} ref={anchor} onClick={event => handleClick(event, menuItem) } > <button className={classes.menuItemBtn} data-test="menu-item-label" data-test-id={menuItem.testingContextId} > {menuItem.iconSrc && <div className={classNames(classes.icon, { [classes.icon]: isMenuShrunk })} > <SVG src={menuItem.iconSrc}/></div>} <Typography aria-label={menuItem.ariaLabel} className={classNames(classes.label, { [classes.hideLabel]: !isMenuShrunk })} variant="body2" > {menuItem.label} </Typography> </button> {menuItem.children && ( <Collapse timeout="auto" unmountOnExit className={classNames({[classes.popper]: open && isMenuShrunk,})} in={open} > <div> {menuItem.children.map(subMenuItem => ( <Typography aria-label={subMenuItem.ariaLabel} component="button" className={classNames({[classes.subColor]:!color , [classes.subMenuLabel]:open||!open, [classes.sublabel]:open||!open})} key={subMenuItem.url} onClick={event => handleClickSubMenu(event, subMenuItem)} data-test="submenu-item-label" data-test-id={subMenuItem.testingContextId} variant="body2" > {subMenuItem.label} </Typography> ))} </div> </Collapse> )} </div>

Possible solutions

First

make your open state a string instead of a boolean move it to the root level and store the opened menu id in it and also change the open condition like this open==='menuId' this will enable you to show only one opened menu at a time

Second

Use context API to wrap the whole menu in it and control the state from the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM