0

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" />}
      />
    }
/>

2 Answers 2

1

You need to wrap the Material UI Autocomplete with the Controller Component provided by React Hook Form. See this section in the documentation for further information.

Edit React Hook Form - MUI Autocomplete

Sign up to request clarification or add additional context in comments.

4 Comments

thanks!! it works fine on codeSandbox, but when I use in my project, I get undefined on "value", when: render={({ field: { value, onChange } }). Do you think could be my version of React Hook form? im using currently: "react-hook-form": "^6.15.3",
Yes, sorry. I used the recent version v7 for the CodeSandbox. With this new version the signature of the render prop function changed. For v6 it would be: render={({ value, onChange }) => ... }.
hey! if You could help a little bit more, im trying to do this since yesterday. Now im using the same component, but now to edit data. I have to set default checked values. At first, it seems to work fine, but if you click a checked button doest work as expected. Here the sandbox: codesandbox.io/embed/…
Autocomplete uses strict equality by default to determine if an option is selected. As your defaultCategory objects don't have the same reference as newCategories, the check will fail. You have to use the getOptionSelected prop to find the correct and corresponding object from newCategories for all your defaultCategory objects. Check the docs for more info. Here is the updated CodeSandbox.
1

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 selected
  • getOptionLabel: to show up the label of the options
  • onChange: use onChange function of react-hook-form to set the selected values
  • renderInput: to render the input
import { 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",
    },
    ...
]

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.