'React.map does not get the selected value
I have a list of items, that is shown correctly with mui list and I have made a button so I can edit the list but when I click on the item I get the value of the last item not the one I clicked on.
This is my function:
const listItems = (id) => {
if (!liste) {
<div>no data</div>
} else {
return (
<List>
<ListItemButton onClick={() => handleClick(id)}>
<ListItemText primary={liste?.[id]?.navn} />
{handleOpen(id) ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={handleOpen(id)} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{liste
.filter((l) => l.tilhors_id === id)
.map((l) => {
return (
<ListItemButton
key={l.id}
sx={{ pl: 4 }}
>
<ListItemText
primary={
<div>
{l.navn}
</div>
}
/>{l.beloeb}{console.log(l.id)}
<EditPost open={openModal} handleOpen={handleOpenModal} id={l.id} navn={l.navn} beloeb={l.beloeb} />
<Button>X</Button>
</ListItemButton>
);
})}
</List>
</Collapse>
{liste.filter((k) => k.subtotal === id)
.map((k) => {
return (
<ListItemButton key={k.id}>
<ListItemText primary="Subtotal" />
{k.beloeb}
</ListItemButton>)
})}
</List>
);
}
};
this is my EditPost:
<div>
<ButtonIcon type='button' onClick={handleOpen} ><GrEdit/></ButtonIcon>
<Modal tittel='Login' open={open} handleOpen={handleOpen} >
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<Chip label={navn} color='info' />
<Controller
control={control}
name="beloeb"
render={({ field: { onChange, onBlur, value, ref } }) =>
<Text
label="Beløb"
onChange={onChange}
onBlur={onBlur}
selected={value}
/>
}
type="number"
InputLabelProps={{
shrink: true,
}}
/>
</div>
<CustomizedButtons type="submit" label="Gem" disabled={isLoading} />
</form>
</Modal>
</div>
I just don't understand why it doesn't get the selected value
EDIT
Solution 1:[1]
The sandbox helps! I took a look at the DOM, a modal instance is declared per rendered list item. So, after initial render, if only the first list, containing one item, is expanded, you'll render the expected modal. If the first two lists are expanded, you've know created eight modal instances at the bottom of the DOM (elements with attribute role value "presentation") and thus the latest instance is opened.
I haven't coded this solution, but what I would do is remove Modal from EditPost so that you are not rendering multiple Modal instances; rendering a singular instance in App.js would be a more appropriate alternative. From there, dynamically generate the contents of the modal instance via props.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | qslabs |
