Search code examples
javascriptreactjsdrop-down-menumaterial-uimenu

MUI: How to handle multiple dropdowns


I'm using MUI to create a navigation menu which has some dropdowns in some of it's links. This is my code, but each button i click opens the same dropdown menu.

function Header() {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);
  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <StyledHeader>
      <Nav>
        <Link href='/'>
          <Logo color='#fff' width='180' />
        </Link>

        <MenuList>
          {HeaderMenu.map((item, i) => {
            return (
              <>
                <MainMenuItem
                  key={i}
                >
                  Button
                    variant='text'
                    color='secondary'
                    onClick={handleClick}
                    endIcon={
                      item.submenu ? (
                        <IconArrowDown width='14' color='#fff' />
                      ) : null
                    }
                  >
                    {item.title}
                  </Button>
                  {item.submenu && (
                    <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
                      {item?.submenu.map((subItem) => {
                        return (
                          <>
                            <MenuItem onClick={handleClose}>
                              {subItem.title}
                            </MenuItem>
                          </>
                        );
                      })}
                    </Menu>
                  )}
                </MainMenuItem>
              </>
            );
          })}
        </MenuList>
      </Nav>
    </StyledHeader>
  );
}

How do i reference the dropdown of each button?

Here's a screenshot also:

enter image description here

Eve though i clicked on "Home", it shows the "About" dropdown, and it shows the same dropdown on whichever menu item i click.

Any help would be appreciated!


Solution

  • I think part of your issue is this:

      <Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
       ...
      </Menu>
    

    It would seem that all submenus have their open and anchorEl props controlled by the same state. This would mean they are all open or all closed. And anchored to whatever you clicked.

    I bet if you inspect it, you have multiple menus displayed on top of each other

    Instead of just defining const open = Boolean(anchorEl), which would be true whenever you've clicked a button, perhaps track the title of the menu being opened.