Reputation: 155
I am trying to use Material UI multiselect with checkboxes. So far, I am able to make multiple selects and get the values but I am unable to render the actual names of selected values or get all selected values. Any leads to a new approach I can use or useful links to help get the ids of all selected values in my array will be appreciated.
I created a sandbox that has a mock of my data from an api as well here : sandbox
My select looks like this :
const [selected, setSelected] = useState([]);
const isAllSelected =
options.length > 0 && selected.length === options.length;
const handleChange = (event) => {
console.log("vals", event.target);
const value = event.target.value;
if (value[value.length - 1] === "all") {
setSelected(selected.length === options.length ? [] : options.title);
return;
}
setSelected(value);
console.log("values", selected);
};
<FormControl className={classes.formControl}>
<InputLabel id="mutiple-select-label">Multiple Select</InputLabel>
<Select
labelId="mutiple-select-label"
multiple
variant="outlined"
value={selected}
onChange={handleChange}
renderValue={(selected) => selected}
MenuProps={MenuProps}
>
<MenuItem
value="all"
classes={{
root: isAllSelected ? classes.selectedAll : ""
}}
>
<ListItemIcon>
<Checkbox
classes={{ indeterminate: classes.indeterminateColor }}
checked={isAllSelected}
indeterminate={
selected.length > 0 && selected.length < options.length
}
/>
</ListItemIcon>
<ListItemText
classes={{ primary: classes.selectAllText }}
primary="Select All"
/>
</MenuItem>
{options.map((option) => (
<MenuItem key={option.id} value={option.id}>
<ListItemIcon>
<Checkbox checked={selected.includes(option.id)} />
</ListItemIcon>
<ListItemText primary={option.title} />
</MenuItem>
))}
</Select>
<p>{selected}</p>
</FormControl>
Upvotes: 0
Views: 3600
Reputation: 1651
I did a few fix in your code so it works, in this sandbox:
To display some text in your menu, you are supposed to display the text in the component ListItemText
:
<ListItemText>{option}</ListItemText>
An other thing is that you cannot access selected
directly, since it is a state, so it is set asynchronously. To solve this, you can simply access it like this:
selected?.length
This way, even if selected is still undefined, it will not throw any errors
Upvotes: 1