Reputation: 87
I am using the component 'AutoComplete' of material Ui to render multiple Checkboxes, and show the options selected into a TextField. The error occurs when I submit the form. The values of checkboxes selected are empty, like this: category: "" It seems the react hook form is not recognizing the name "category", like below:
<Autocomplete
id="checkboxes-tags-demo"
fullWidth
multiple
limitTags={2}
getOptionLabel={(option) => option.title}
disableCloseOnSelect
noOptionsText="Nenhuma opção foi encontrada"
variant="outlined"
options={newCategories}
renderOption={(option, {selected}) => {
return (
<Box key={option.id} ml={option?.isSub ? 3 : 0}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
checked={selected}
/>
{option.title}
</Box>
)
}
}
renderInput={(params) =>
<TextField
name="category"
inputRef={register}
{...params}
label="Selecione a categoria"
variant="outlined" />}
/>
}
/>
Upvotes: 0
Views: 2732
Reputation: 8388
Here is the correct way to set up the autocomplete for multiple values:
multiple
to add multiple values,options
: you add the options to be selectedgetOptionLabel
: to show up the label of the optionsonChange
: use onChange function of react-hook-form
to set the selected valuesrenderInput
: to render the inputimport { useForm, Controller } from 'react-hook-form'
import {
Box,
TextField,
Autocomplete,
} from '@mui/material'
const {
...
control,
formState: { errors },
} = useForm()
<Box mt={2}>
<Controller
control={control}
name="industries"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange } }) => (
<Autocomplete
defaultValue={
useCasesData?.industries
? JSON.parse(useCasesData?.industries)
: []
}
multiple
disableCloseOnSelect
options={companyIndustryTypes}
getOptionLabel={(option) => option.name}
onChange={(event, values) => {
onChange(values)
}}
renderInput={(params) => (
<TextField
{...params}
label="Type d'industries"
placeholder="Type d'industries"
helperText={errors.industries?.message}
error={!!errors.industries}
/>
)}
/>
)}
/>
</Box>
Note that options in my case
companyIndustryTypes
is an array of object :
[
{
id: 1,
name: "Accounting",
},
{
id: 2,
name: "Administration & Office Support",
},
...
]
Upvotes: 1