I am using Chip from "@mui/material/Chip" and Select from "@mui/material/Select"; in my react js application.
import * as React from "react";
import { useTheme } from "@mui/material/styles";
import Box from "@mui/material/Box";
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 Select from "@mui/material/Select";
import Chip from "@mui/material/Chip";
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
PaperProps: {
style: {
maxHeight: ITEM_HEIGHT * 4.5 ITEM_PADDING_TOP,
width: 250
}
}
};
const names = [
{
id: 1,
name: "Carl"
},
{
id: 2,
name: "Bill"
}
];
function getStyles(name, personName, theme) {
return {
fontWeight:
personName.indexOf(name) === -1
? theme.typography.fontWeightRegular
: theme.typography.fontWeightMedium
};
}
export default function MultipleSelectChip() {
const theme = useTheme();
const [personName, setPersonName] = React.useState([1]);
const handleChange = (event) => {
const {
target: { value }
} = event;
setPersonName(
// On autofill we get a the stringified value.
typeof value === "string" ? value.split(",") : value
);
};
console.log(personName, "get a list of ids");
return (
<div>
<FormControl sx={{ m: 1, width: 300 }}>
<InputLabel id="demo-multiple-chip-label">Chip</InputLabel>
<Select
labelId="demo-multiple-chip-label"
id="demo-multiple-chip"
multiple
value={personName}
onChange={handleChange}
input={<OutlinedInput id="select-multiple-chip" label="Chip" />}
renderValue={(selected) => (
<Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.5 }}>
{selected.map((value) => (
<Chip key={value} label={value} />
))}
</Box>
)}
MenuProps={MenuProps}
>
{names.map(({ id, name }) => (
<MenuItem
key={name}
value={id}
style={getStyles(name, personName, theme)}
>
{name}
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
}
I now if i added as initial value an id, in the dropdown it also show as number, but i need to set there the name
of the user from the array. Also when i will change the input data in console.log(personName, "get a list of ids");
i want to see a list of ids, like now. The issue is next: now the dropdown initial value is 1
but it should be Carl
, because he has id 1, also when i select Bill
there appear nr 2
, but i need the text instead the number.
Who can help with this?
demo: https://codesandbox.io/s/multipleselectchip-material-demo-forked-lkhzb?file=/demo.js:1264-1309
CodePudding user response:
Try rendering the Chip
s this way:
<Chip key={value} label={names.find(element => element.id === value).name} />
personName
will remain list of ids but you'll render the relevant names.