1

I'm currently having issues with controlling an autocomplete MUI component with react-hook-form's <controller> component.

Here's the code:

<Controller
  control={control}
  name="rooms"
  render={({ field }) => (
    <Autocomplete
      multiple
      limitTags={6}
      // data is formatted like this: [{label: string, value: number}]
      options={data}
      filterSelectedOptions
      style={{ minWidth: '350px', maxWidth: '30%' }}
      renderInput={params => (
        <TextField
          {...params}
          variant="outlined"
          label="Rooms"
          placeholder="Search"
        />
      )}
      {...field}
    />
  )}
/>

Here's my issue: When setting up a controller element on it, the returned value on the submition of our form will always be 0 for some reason.

Example: I'm selecting two rooms, Bathroom(with id 1) and Kitchen(with id 0). The expected output would be: rooms: [{label: 'Bathroom', value: 1}, {label: 'Kitchen', value: 0}] but i'm getting rooms: 0 instead.

There's another forum on this topic, however it has been unactive for over two years, and none of the given answers seem to work.

Here's my packages versions:

  • react-hook-form (7.43.9)
  • @material-ui/core (4.12.4)

Thanks in advance for your help and advices !

1 Answer 1

4

I found the answer. The problem was how I wrote my render props:

Here's the functionnal render code:

render={({ field }) => {
  const { onChange, onBlur, value } = field;
  return (
    <Autocomplete
      multiple
      limitTags={6}
      options={data}
      filterSelectedOptions
      style={{ minWidth: '350px', maxWidth: '30%' }}
      renderInput={params => (
        <TextField
          {...params}
          variant="outlined"
          label="Rooms"
          placeholder="Search"
        />
      )}
      onChange={(event, selectedOptions) => {
        onChange(selectedOptions);
      }}
      onBlur={onBlur}
      value={value}
    />
  );
}}

Explanation of the issue:

I was only passing the field object to the <Autocomplete> component, which means I was not updating the value correctly. By destructuring the onChange, onBlur, and value from the field object and passing them to the corresponding props of <Autocomplete>, it is ensuring that the selected options are properly updated and stored in the form's state when using react-hook-form.

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

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.