Reputation: 692
I'm new to Material UI and trying to integrate a select all option in material multiselect. I have a array of object
const names = [
{ id: 0, name: "Oliver Hansen" },
{ id: 1, name: "Van Henry" },
{ id: 2, name: "April Tucker" }
];
I'm iterating over this array and displaying the value in multiselect. Below is the code for Multiselect
<FormControl className={classes.formControl}>
<InputLabel id="demo-mutiple-checkbox-label">Tag</InputLabel>
<Select
labelId="demo-mutiple-checkbox-label"
id="demo-mutiple-checkbox"
multiple
value={personName}
onChange={handleChange}
input={<Input />}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
<MenuItem
value="all"
classes={{
root: isAllSelected ? classes.selectedAll : ""
}}
>
<ListItemIcon>
<Checkbox
classes={{ indeterminate: classes.indeterminateColor }}
checked={isAllSelected}
indeterminate={
personName.length > 0 && personName.length < names.length
}
/>
</ListItemIcon>
<ListItemText
classes={{ primary: classes.selectAllText }}
primary="Select All"
/>
</MenuItem>
{names.map((item, index) => (
<MenuItem key={item.id} value={item.id}>
<Checkbox checked={personName.indexOf(item.id) > -1} />
<ListItemText primary={item.name} />
</MenuItem>
))}
</Select>
</FormControl>
In the select option i'm giving value as id and text as name, But when i select any option it will display me the value in place of name.
Which is correct in one sense but i want to display only name in the select field not its id which i associated to the value.
Also selectAll is acting as a indiviual option not selection all the values.
Upvotes: 0
Views: 3823
Reputation: 2053
If you have id you can find object which belongs to it and then use only the name.
renderValue={
(selected) =>
names.filter( name => selected.includes(name.id) )
.map( record => record.name )
.join(", ")
}
Upvotes: 2