Ad

How To Fix Problem With Multiple Menu Item From Material Ui

- 1 answer

When I try to put Menu component many times I get wrong popup list. I show my problem on codesandbox link below. I put data-id attributes to show in chromedev is popu list is correct.

https://wt7jy.csb.app/

     <Button
        aria-controls="simple-menu"
        aria-haspopup="true"
        onClick={handleClick}
      >
        Open Menu
      </Button>
      <Menu
        id="simple-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose} data-id="1">
          Profile
        </MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>

      <Button
        aria-controls="simple-menu2"
        aria-haspopup="true"
        onClick={handleClick}
      >
        Open Menu
      </Button>
      <Menu
        id="simple-menu2"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose} data-id="2">
          Profile
        </MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>
    </div>

I expect to show correct popup list. When I click left data-id should be "1" and on righ shoud by "2" Actually when I click on list 1 I get "2"

Ad

Answer

I guess the problem with the anchorEl in second Menu. It should be

      <Button
        aria-controls="simple-menu2"
        aria-haspopup="true"
        onClick={handleClick} // Here you have to set target to `anchorEl2`
      >
        Open Menu
      </Button>
       <Menu
        id="simple-menu2"
        anchorEl={anchorEl2}
        keepMounted
        open={Boolean(anchorEl2)}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose} data-id="2">
          Profile
        </MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>

Here is the working demo for you. https://stackblitz.com/edit/react-material-menu-jnnxnc

Ad
source: stackoverflow.com
Ad