I'm displaying a list of users in a table. Each row has a cell which contains a button to delete the user. When the delete button is clicked I'm rendering a Material-UI <Dialog /> component to confirm.
The issue is that the map is causing 3 dialogs to be rendered and the last one is the one on top. So If I have 3 users in the array, 3 dialogs are rendered but you can only interact with the 3rd dialog (it blocks the other 2 from view).
The issue is similar to this one.
Is there a way to control which dialog is opened?
handleDeleteUser is an async function making a request so I need to pass id and links to that method.
I have a simplified codesandbox here. If you try to delete user 1 or user 2, you can see that only the id and link for user 3 appear in the console.
const handleDeleteUser = (id, links) => {
// this always prints the id and links for the last user in the table
console.log("deleting user -->", id);
console.log("user delete URL", links.self);
setOpen(false);
};
<Table.Body>
{userList && userList.length >= 1 ? (
userList.map(
({ id, attributes, links, i }, index) => {
return (
<Table.Row key={index}>
<Table.Cell textAlign="center">
<Button
circular
icon
size="mini"
color="red"
type="button"
onClick={handleClickOpen}
>
<Icon name="delete" />
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
{"Confirm User Delete"}
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
{`Are you sure you want to delete this user?`}
</DialogContentText>
</DialogContent>
<DialogActions>
<MUIButton
type="button"
onClick={handleDeleteUser.bind(
this,
id,
links
)}
color="primary"
>
Yes
</MUIButton>
<MUIButton
type="button"
onClick={handleClose}
color="primary"
autoFocus
>
Cancel
</MUIButton>
</DialogActions>
</Dialog>