My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render.
The scenario involves having a list of items where each item has a menu to perform actions unique to that individual item, such as "Delete", "Edit", etc.
Example that does not work: https://codesandbox.io/s/material-demo-forked-u6902?file=/demo.js
export default function SimpleMenu() {
const [anchor, setAnchor] = React.useState(null);
const handleOpenMenu = (event) => {
setAnchor(event.currentTarget);
};
const handleCloseMenu = (number) => {
console.log(number);
setAnchor(null);
};
return ["one", "two"].map((number) => (
<div key={number}>
<Button onClick={() => handleCloseMenu(number)}>Log {number}</Button>
<Button onClick={(e) => handleOpenMenu(e)}>Menu {number}</Button>
<Menu
anchorEl={anchor}
keepMounted
open={Boolean(anchor)}
onClose={() => handleCloseMenu(number)}
>
<MenuItem onClick={() => handleCloseMenu(number)}>Log Number</MenuItem>
</Menu>
</div>
));
}
If I maintain a map linking array elements to anchors for the Menu, then it functions as expected.
Example that works: https://codesandbox.io/s/material-demo-forked-m7utx?file=/demo.js
export default function SimpleMenu() {
const [anchors, setAnchors] = React.useState({});
const handleOpenMenu = (number, event) => {
setAnchors((prevState) => ({
...prevState,
[number]: event.currentTarget
}));
};
const handleCloseMenu = (number) => {
console.log(number);
setAnchors((prevState) => ({
...prevState,
[number]: null
}));
};
return ["one", "two"].map((number) => (
<div key={number}>
<Button onClick={() => handleCloseMenu(number)}>Log {number}</Button>
<Button onClick={(e) => handleOpenMenu(number, e)}>Menu {number}</Button>
<Menu
anchorEl={anchors[number]}
keepMounted
open={Boolean(anchors[number])}
onClose={() => handleCloseMenu(number)}
>
<MenuItem onClick={() => handleCloseMenu(number)}>Log Number</MenuItem>
</Menu>
</div>
));
}
Is this the correct or intended way to render multiple menus?