I have been trying to build a multiselect dropdown list with checkboxes. The dropdown is being populated by an API call, and I am trying to updated a set of values to write back to the DB. I can get the dropdown to populate, but I cannot seem to get the checkboxes to be checked or set the values.
Dropdown As Called From Page View
<DropdownMultiSelect
onChange={handleInputChange}
label='Materials'
name='materials'
value={values.materials}
prompt='Materials...'
url={MaterialsURL}
/>
Here is my Dropdown Component:
import * as React from 'react';
import axios from 'axios';
import { Checkbox, FormControl, FormHelperText, InputLabel, Select, MenuItem, ListItemText, OutlinedInput } from '@material-ui/core';
import { FormControl, FormHelperText, InputLabel, Select, MenuItem, ListItemText, OutlinedInput } from '@material-ui/core';
export default function dropdownMultiSelect(props) {
const { label, name, handleInputChange, prompt, value, url } = props;
const [options, setOptions] = React.useState([]);
// Fetch Data for Dropdown list
React.useEffect(() => {
const fetchData = async () => {
const res = await axios.get(url);
setOptions( res.data);
};
fetchData();
}, []);
return (
<FormControl variant='outlined' >
<InputLabel>{label}</InputLabel>
<Select
multiple
name={name}
value={value}
onChange={handleInputChange}
renderValue={(selected) => selected.map((x) => x.materialName).join(', ')}
>
{options.map((option, id) => (
<MenuItem
key={option.id}
value={option.id}
>
<Checkbox checked={value?.includes(option.id)} />
{option.name}
</MenuItem>
))}
</Select>
</FormControl>
);
}
I am using the same onChange event that I have used for the rest of my form to catch the input change and set the values.
OnChange Event:
const [values, setValues] = React.useState({} as any);
const [errors, setErrors] = React.useState({} as any);
const handleInputChange = e => {
const { name, value } = e.target;
setValues({
...values,
[name]: value
});
if (validateOnChange) { validate({ [name]: value }); }
};
Can someone please show me what I am doing wrong so I can get this thing working.
Adding name to MUI Multiple select may solve this issue.
Since React is a one way binding modal, make sure that you are passing right value back to Multiple select component.
<Select multiple value={value} onChange={handleInputChange} renderValue={selected => selected.map(x => x?.name).join(', ')} name='nameYouLike' // HERE > {options.map((option, id) => ( <MenuItem key={option.id} value={option.id}> <Checkbox checked={value?.includes(option.id)} /> {option.name} </MenuItem> ))} </Select>
Ref: https://mui.com/material-ui/react-select/#multiple-select