Home > database >  How to get selected checkbox value and id from the multi select in MUI
How to get selected checkbox value and id from the multi select in MUI

Time:07-25

I am using MUI select component with multi-select. The multi-select rendering uses the below JSON array. Is there any way we can get both the selected item id and value?

Here is the code sandbox URL :https://codesandbox.io/s/cranky-currying-ce8djy?file=/src/App.js

JSON Array: const menuItems = [
  { id: "8271e42a-8982-44b8-9745-3271e0cf9d12", value: "Item 1" },
  { id: "c0f3e462-02f8-4d8d-ae05-6965b7902a80", value: "Item 2" },
  { id: "c0f3dfyh-02f8-4d8d-ae05-6965b7dw3456", value: "Item 3" }
];



 export default function App() {
  const [selected, setSelected] = useState([]);

  const handleChange = (event) => {
    const {
      target: { value }
    } = event;
    setSelected(typeof value === "string" ? value.split(",") : value);
    console.log(selected);
  };

  const ITEM_HEIGHT = 48;
  const ITEM_PADDING_TOP = 8;

  const lteProps = {
    PaperProps: {
      style: {
        maxHeight: ITEM_HEIGHT * 4.5   ITEM_PADDING_TOP,
        width: 250
      }
    }
  };
  return (
    <div className="App">
      <FormControl fullWidth={true}>
        <Select
          multiple
          value={selected}
          onChange={handleChange}
          renderValue={(selected) => selected.join(", ")}
          MenuProps={lteProps}
        >
          {menuItems.map((item) => (
            <MenuItem key={item.id} value={item.value}>
              <Checkbox checked={selected.indexOf(item.value) > -1} />
              <ListItemText primary={item.value} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Appreciate any help.

CodePudding user response:

I worked before on MUI.
You need to add one more parameter to the handleChange function to access ID. But it is currently returning ID with .$. So you have to filter these two chars.

  const handleChange = (event,obj) => {
    const {
      target: { value }
    } = event;
    setSelected(typeof value === "string" ? value.split(",") : value);
    // on selecting first option, will return
    // .$8271e42a-8982-44b8-9745-3271e0cf9d12
    console.log(obj.key);
  };
  • Related