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.
Here is my Dropdown:
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
value={value}
onChange={handleInputChange}
renderValue={(selected) => selected.map((x) => x.name).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.