I have a multi select that i pass an object into the value property with the structure:
The select component looks like this:
<Select
multiple
value={entities}
onChange={handleChange}
input={<Input />}
renderValue={(selected) => (
<div className={classes.chips}>
{selected.map((value) => (
<Chip
key={value.entityId}
label={value.entityName}
className={classes.chip}
/>
))}
</div>
)}
>
{props.entityList.map((item, index) => (
<MenuItem key={item.entityId} value={item}>
{item.entityName}
</MenuItem>
))}
</Select>
when the select pops up it shows the entity name correct but does not show it as selected in the dropdown.
If i select this item in the drop down it adds another entry which has the same id and same name rather than removing the item that is already there, this newly added duplicate can be removed and is highlighted when selected so the functionality works somewhat.
I am storing entities
in the state like so that comes in from a parent component:
Solution:
I have made sure that the same object is being used across the select, the initial object was not the same as the objects that where being assigned in the on Change function. this fixed my problem.
const [entities, setEntity] = React.useState(
props.entityList.filter((e) =>
props.assignedEntities.some((ae) => e.entityId === ae.entityId)
)
);
Select
, they will only be considered matching if they are the exact same object. Two different objects that happen to have the same content will not be considered matching. – Boprops.entityList
andprops.assignedEntities
are managed), it is difficult to recommend a solution. My suspicion is thatprops.assignedEntities
has separate copies of the objects inprops.entityList
rather than reusing the exact same objects. I would recommend initializing yourentities
state usingprops.entityList.filter(...)
where you filter by the assigned entity ids such thatentities
is guaranteed to reuse objects fromprops.entityList
. – Bo