I am implementing a styled multiple select dropdown and am able to load the menu items from the local database. However, I have 2 problems:
- The checkbox doesn’t seem to update when the menu item is clicked.
- The values displayed in the dropdown after clicked is the value used to pass and store in the database. How do I make it display like the dropdown list item? I did try to type
selected[i18n.language].join(', ')
but it throws an error after clicking on a menu item: Cannot read property ‘join’ of undefined
Since the values are loaded from local database, I am unable to provide CodeSandbox link. The code is based on the example provided by the Material UI documentation.
I modified it to suit my requirement for the form.
This is the data from the database that is use to load into the multi select dropdown menu:
Portion of code used to retrieve the values from database
const [tbtItems, setTbtItems] = useState([]);
const [tbtItemsSelected, setTbtItemsSelected] = useState([]);
async function getPTLCodeTable() {
let PTLCodeTable = JSON.parse(sessionStorage.getItem("PTLCodeTable"));
console.log("codeTable get from session: ", PTLCodeTable);
if (PTLCodeTable === null || PTLCodeTable === undefined) {
const response = await fetch(url + "code/getPTLCode", codeTableRequest);
const body = await response.json();
if (body.message == "Success") {
sessionStorage.setItem("PTLCodeTable", JSON.stringify(body.data));
}
}
}
useEffect(() => {
async function getCharacters() {
let PTLCodeTable = JSON.parse(sessionStorage.getItem("PTLCodeTable"));
if (PTLCodeTable !== null && PTLCodeTable !== undefined) {
setTbtItems(
PTLCodeTable.tbt.map(({ id, en }) => ({
id: id,
en: en,
}))
);
console.log("set by session");
}
}
if (tbtItems.length <= 0)
getCharacters();
});
Selection Element
<Controller
control={control}
name={`premiseArray[${index}].businessTypes`}
defaultValue={item.businessTypes}
render={(props) => {
return (
<Select
id={`premiseArray[${index}].businessTypes`}
multiple
defaultValue={item.businessTypes}
onChange={(value) => {
props.onChange(value);
}}
input={<Input />}
renderValue={(selected) => selected.join(", ")}
MenuProps={{
getContentAnchorEl: null,
}}
{...props}
>
{tbtItems.map((item) => (
<MenuItem key={item.id} value={item.id}>
<Checkbox checked={tbtItemsSelected.indexOf(item.id) > -1} />
<ListItemText primary={item[i18n.language]} />
</MenuItem>
))}
</Select>
);
}}
/>;
Any help is much appreciated.