MenuItem
allows for a style rule to be applied to the selected item using the classes prop with the key name selected
. In order for this functionality to work, the item must also have a boolean prop called select
, indicating whether the item is selected or not.
const StyledMenuItem = withStyles((theme) => ({
root: {
"&:focus": {
backgroundColor: theme.palette.primary.main,
},
},
selected: {
color: "red",
}
}))(MenuItem);
export default function CustomizedMenus() {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const [selected, setSelected] = React.useState(null);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleMenuItemClick = (e, index) => {
setSelected(index);
};
const menuArr = [
{
Icon: SendIcon,
text: "Sent mail"
},
{
Icon: DraftsIcon,
text: "Sent mail"
},
{
Icon: InboxIcon,
text: "Inbox"
}
];
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}
>
{menuArr.map((item, index) => (
<StyledMenuItem
selected={index === selected}
onClick={(event) => handleMenuItemClick(event, index)}
>
<ListItemIcon>
<item.Icon fontSize="small" />
</ListItemIcon>
<ListItemText primary={item.text} />
</StyledMenuItem>
))}
</StyledMenu>
</div>
);
}
For a live demo, click here:
https://codesandbox.io/s/material-demo-forked-wtsrj?fontsize=14&hidenavigation=1&theme=dark