Material UI Menu not closing after clicking a menu item
Asked Answered
W

7

19

This is code straight from MUI menu - customized menu.. I didn't want to put my code because there are some built in functions that make it more confusing.

In my code (not this) I open a MUI Dialog when a menu item is clicked. The issue is that the menu does not go away after the Dialog is submitted.

I would like to know how to make the menu close as soon as anything on the menu is clicked(menu items).

Thanks

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Menu, { MenuProps } from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import DraftsIcon from '@material-ui/icons/Drafts';
import SendIcon from '@material-ui/icons/Send';

const StyledMenu = withStyles({
  paper: {
    border: '1px solid #d3d4d5',
  },
})((props: MenuProps) => (
  <Menu
    elevation={0}
    getContentAnchorEl={null}
    anchorOrigin={{
      vertical: 'bottom',
      horizontal: 'center',
    }}
    transformOrigin={{
      vertical: 'top',
      horizontal: 'center',
    }}
    {...props}
  />
));

const StyledMenuItem = withStyles((theme) => ({
  root: {
    '&:focus': {
      backgroundColor: theme.palette.primary.main,
      '& .MuiListItemIcon-root, & .MuiListItemText-primary': {
        color: theme.palette.common.white,
      },
    },
  },
}))(MenuItem);

export default function CustomizedMenus() {
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <div>
      <Button
        aria-controls="customized-menu"
        aria-haspopup="true"
        variant="contained"
        color="primary"
        onClick={handleClick}
      >
        Open Menu
      </Button>
      <StyledMenu
        id="customized-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <StyledMenuItem>
          <ListItemIcon>
            <SendIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText primary="Sent mail" />
        </StyledMenuItem>
        <StyledMenuItem>
          <ListItemIcon>
            <DraftsIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText primary="Drafts" />
        </StyledMenuItem>
        <StyledMenuItem>
          <ListItemIcon>
            <InboxIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText primary="Inbox" />
        </StyledMenuItem>
      </StyledMenu>
    </div>
  );
}
Walkout answered 19/6, 2020 at 1:32 Comment(1)
What does keepMounted use for?Salmon
P
21

You can just assign handleClose handler to the onClick property of the <Menu> itself like this:

<StyledMenu
  onClick={handleClose}
  onClose={handleClose}
  {...yourProps}
>
 ...
</StyledMenu>
Peninsula answered 11/1, 2021 at 16:13 Comment(1)
That did the trick, it feels strange but it works!!Scheller
C
9

You can put an onClick prop to the MenuItem:

<StyledMenuItem onClick={handleClose}>Text</StyledMenuItem>
Cleavers answered 19/6, 2020 at 1:50 Comment(1)
Thanks! This solved my issues over a year after you wrote it!Susannesusceptibility
M
6

I had a similar issue, couldn't apply hangindev.com solution to my problem. Only difference was that my menu items were children passed outside of the menu component. You could use the onBlur event on StyledMenu.

<StyledMenu
    id="customized-menu"
    anchorEl={anchorEl}
    keepMounted
    open={Boolean(anchorEl)}
    onClose={handleClose}
    onBlur={handleClose}
  >{children}<StyledMenu>

Sorry for posting after 2 years, I hope this contributes. I used @mui/material 5.4.0 version.

Monahan answered 3/5, 2022 at 9:22 Comment(1)
Thanks, keepMounted was crucial for me since I was passing a Dialog a a child to the Menu.Excruciate
G
2

I ran into the same issue and the top voted answer wasn't working for me. Instead of fighting Material UI, I kept it simple and this is working great:

{anchorElUser ? (
  <Menu
    anchorEl={anchorElUser}
    open={true}
    onClose={handleClose}
    onClick={handleClose}
  >
    {menuItems.map(...)}
  </Menu>
) : null}
Glossa answered 28/10, 2023 at 18:38 Comment(1)
fixed the issue for me thanks so muchBourgeoisie
F
1

onBlur={handleClose} works correctly if pass comp as children for other

Fann answered 18/8, 2022 at 8:59 Comment(0)
O
0

we may use onClick instead of onClose in

   <StyledMenu
        id="customized-menu"
        anchorEl={anchorEl}
        keepMounted
        open={Boolean(anchorEl)}
        onClick={onClose}
    >
Ornelas answered 6/6, 2022 at 15:22 Comment(0)
R
0

I too had this same issue in MUI menu

So as a solution I disabled the portal and unsetted the zIndex to MUI Menu component.

enter image description here

<Menu
  sx={{
    zIndex: { xs: 1300, md: 'unset' },
  }}
  disablePortal
>
  // Lists  
</Menu>
Ric answered 26/7, 2023 at 9:10 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Disinfectant

© 2022 - 2024 — McMap. All rights reserved.