skip to Main Content

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


  1. 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 type SelectChangeEvent 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.

    Login or Signup to reply.
  2. You don’t have a consistent value. In MenuItem you are using the below logic.

    value={obj.accountNumber ? obj.accountNumber : obj.label}
    

    But in Checkbox you are checking if its checked based on

    checked={selectedVal.indexOf(obj.label) > -1}
    

    Try to keep the value consistent in both MenuItem and Checkbox.

    {data.length > 0 ? (
      data.map((obj) => {
        const value = obj.accountNumber ? obj.accountNumber : obj.label;
        return <MenuItem
          key={obj.label + obj.accountNumber}
          value={value}
        >
          <Checkbox checked={selectedVal.indexOf(value) > -1} />
          <ListItemText primary={obj.label} />
        </MenuItem>
      })
    ) : (
      <MenuItem>None</MenuItem>
    )}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search