Recently I tried to implement a simple dropdown menu using MaterialUI(4.3.3)'s Menu and MenuItem components.
The onclick event on the MenuItem is not behaving correctly. When console.log(id)
is called, every component is echoing the last element from sample array. I switched to ListItem, the problem is gone.
const Test = () => {
const [anchorEl, setAnchorEl] = React.useState(null);
const sampleArray = ["test1", "test2", "test3"];
const open = Boolean(anchorEl);
return (
sampleArray.map(id => {
let curID = id;
return (<>
<IconButton
aria-label="more"
aria-controls="long-menu"
aria-haspopup="true"
onClick={event => setAnchorEl(event.currentTarget)}
>
<MoreHorizIcon />
</IconButton>
<Menu
elevation={0}
id="long-menu"
anchorEl={anchorEl}
keepMounted
open={open}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
onClose={() => setAnchorEl(null)}
>
<MenuItem onClick={() => {
setAnchorEl(null);
console.log(curID); // should be each individual id, but here always "test3"
}}>Test</MenuItem>
</Menu>
</>);
})
)
}
Is this the desired behavior for Menu? How to resolve it?