React-Hook-Form setValue for Material-UI Autocomplete doesn't work

Viewed 1339

I'm building a form with React-Hook-Form and Material-UI. Each Material-UI form component is wrapped into a react-hook-form Controller component.

The user has the option to populate the form automatically with different sets of pre-defined values when clicks on a button. I'm trying to use setValue() to achieve that and it seems to work fine for text input and select. However, for autocomplete the new value is not rendered although when submitting the form it is correctly sent. Also, when a text area is rendered the content seems to be mixed with the label.

Here is a complete example: CodeSandbox Link

1 Answers

You need to cotroll the value of AutoComplete by passing value attribute to AutoComplete component, But since you are using string value you couldn't pass value to AutoComplete directly and you should to find the target option like this:

<Autocomplete
      ...
      value={typeof value === 'string' ? options.find(o => o.name === value) : (value || null)}
    />

Your textarea problem occurs because your value by default is undefined and material considers the textare as uncotrolled input, to solve it you can pass empty string when value is undefined, like this:

<TextField
        ...
        value={value || ''}
        ...
  />
Related