react-hook-form: MUI Autocomplete does not work with controlled

Describe the bug

The Material-UI Autocomplete component does not work in the same way as the other TextField components when used with RHF’s Controller.

I am trying to make the component controlled, following the definitions in React.js and with that I came across an example of the integration in the documentation of RHF https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r?file=/src/MuiAutoComplete.js that if I take it to my code it generates the following warnings.

image

when adding defaultValue='' (as it would be done in the other cases) it generates the following warnings and errors in console.

image

To Reproduce Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/react-hook-form-v6-controller-qsd8r?file=/src/MuiAutoComplete.js
  2. Copy example of integration componente Autocomplete
  3. Implement example in your aplication with Material-UI 4.11.0
  4. Review errors and warnings

Codesandbox link (Required)

https://codesandbox.io/s/integration-material-ui-autocomplete-with-react-hook-form-7dhi2?file=/src/App.js

Expected behavior

The expected thing is that it works in the same way as the other components such as TextField do since they do not generate this type of warnings or errors in the console when setting defaultValue=''

Screenshots

image

Desktop (please complete the following information):

  • OS: Windows
  • Browser Chrome latest

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 32 (20 by maintainers)

Most upvoted comments

@vicasas getOptionSelected compares the instances of value and option by default, you’ll have to overwrite it like this, if you use the defaultValue on the Controller.

getOptionSelected={(option, value) => option.label === value.label}

https://codesandbox.io/s/integration-material-ui-autocomplete-with-react-hook-form-forked-eb1g5

still not react-hook-form related @vicasas how about something like:

getOptionSelected={(option, value) => option.code === value.code}
defaultValue={countries.find(({code}) => code === "PL")}

https://material-ui.com/api/autocomplete/

and pro-tip: if you paste errors as text, it’s easier to Google it, and find the issue 😃 For anybody who has this problem in the future:

Material-UI: The value provided to Autocomplete is invalid.
None of the options match with … .
You can use the `getOptionSelected` prop to customize the equality test. 

Yep, I solved the main issue, but the last warning isn’t something that I think MUI allows for when cascading. It’s also not supposed to equal anything when switching to blank in the bottom MUI component.