I am using this mui multi select and need to know if the item is selected or unselected to set the right state value.I checked event.target
but there doesnt seem to be a checked
literal
This is my mui code
<FormControl sx={{ m: 1, width: 300 }}>
<InputLabel id="demo-multiple-checkbox-label">Tag</InputLabel>
<Select
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
multiple
value={selectedVal}
onChange={handleChange}
input={<OutlinedInput label="Tag" />}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{console.log(data)}
{data.length > 0 ? (
data.map((obj) => (
<MenuItem
key={obj.label + obj.accountNumber}
value={obj.accountNumber ? obj.accountNumber : obj.label}
>
<Checkbox checked={selectedVal.indexOf(obj.label) > -1} />
<ListItemText primary={obj.label} />
</MenuItem>
))
) : (
<MenuItem>None</MenuItem>
)}
</Select>
</FormControl>
This is my change handler
const handleChange = (event) => {
const {
target: { value },
} = event;
console.log("value");
console.log(event["target"].checked);
setSelectedVal(
// On autofill we get a stringified value.
typeof value === "string" ? value.split(",") : value
);
};
2
Answers
Your code seems to assume that the
event
your change handler gets is a standard browser DOM event. It is not. It is an MUI event object of typeSelectChangeEvent
and it will have the properties of that object.See the code examples in this section of the MUI docs. In particular I find the code of the "Checkmarks" TypeScript example to be quite informative.
You don’t have a consistent
value
. In MenuItem you are using the below logic.But in Checkbox you are checking if its checked based on
Try to keep the
value
consistent in both MenuItem and Checkbox.