0

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.

Here is the sandbox link

1 Answer 1

2

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(", ")
}
Sign up to request clarification or add additional context in comments.

8 Comments

what about select all ?
Can you also suggest on selectAll
1 doubt, on selecting select all it will return empty array on deselect it will return array with all values ?
When you click select all it return array with all id's, and when deselect all it return empty array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.