Changing Autocomplete value using react-hook-form (Material-UI)

Viewed 779
1 Answers

If you look at console when you change user_name field, you can see materialUI warning in the console which says:

Material-UI: A component is changing the uncontrolled value state of Autocomplete to be controlled.

it's reason is that your user_country's value by default is undefined and material consider this field as uncontrolled field, it means material will take the control of user_country value. To solve the problem you have two solutions:

1- Defining your form by defaultValues options like this:

const methods = useForm({
  defaultValues: {
    user_name: null,
    user_country: null
  }
});

2- Sending null as value to AutoComplete when it doesn't have any value, like this:

<Controller
  control={control}
  name={`user_country`}
  render={({ field: { onChange, value } }) => (
    <Autocomplete
      id="country-select-demo"
      options={countries}
      onChange={(event, item) => {
        onChange(item);
      }}
      value={value || null}
      ...
    />
  )}
/>

Here You can see your form which updates user_country whenever you change user_name field.

Related