I use Material Multiple select to select employees as shown on the following demo:
However, I display id values of the selected employees, but I want to display names of the selected employees. For this purpose, I used another hook, called names
, but still could not.
Here i the code (I cannot share on sandbox, but you can paste directly and check):
demo.js:
import * as React from "react";
import OutlinedInput from "@mui/material/OutlinedInput";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import ListItemText from "@mui/material/ListItemText";
import Select from "@mui/material/Select";
import Checkbox from "@mui/material/Checkbox";
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
width: 250,
},
},
};
const employees = [
{
id: 1,
name: "Rozele",
},
{
id: 2,
name: "Pat",
},
{
id: 3,
name: "Farlee",
},
{
id: 4,
name: "Eddie",
},
{
id: 5,
name: "Ingram",
},
];
export default function MultipleSelectCheckmarks() {
const [names, setNames] = React.useState([]);
const [ids, setIds] = React.useState([]);
const handleChange = (event) => {
const {
target: { value },
} = event;
setIds(value);
// I need to set names by matching value and employee id
//setNames(employees.indexOf(...));
};
return (
<div>
<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={ids}
onChange={handleChange}
input={<OutlinedInput label="Tag" />}
renderValue={(selected) => selected.join(", ")}
MenuProps={MenuProps}
>
{employees.map((employee) => (
<MenuItem key={employee.id} value={employee.id}>
<Checkbox checked={ids.includes(employee.id)} />
<ListItemText primary={employee.name} />
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
}
Any idea?
2
Answers
You don’t need another state to get the names of the employees. You can use a derived variable.
To display the correct name values in the input box we can use the
ids
.