reactjsmaterial-uireact-hook-formmui-autocomplete

Use Material UI autocomplete in freeSolo mode with react-hook-form


I'm trying to use the Material UI's autocomplete in free solo mode as a kind of a combo-input. The user should be able to either select a suggested option via autocomplete or if no option is available, the input value should be used as the final form value.

The problem:

Case one: autocomplete works and suggests options that can be selected and are submitted but when the input has a custom value it does not get submitted.

https://codesandbox.io/s/autocomplete-free-solo-case-1-i7kin?file=/demo.js

Case two: selected options from autocomplete and custom input values are submitted BUT the autocomplete dropdown does not show suggestions anymore, but rather stays open the whole time the input is selected

https://codesandbox.io/s/autocomplete-free-solo-case-2-uk9db?file=/demo.js

I could live with case two because my autocomplete lists have just a few options, but if anyone has some hint or a solution I'd really appreciate it.


Solution

  • You are using the freeSolo, but you didn't add the autoSelect option, so the problem with your code is that when the input lose focus - the value is still the old one. The reason here is that you are using a controlled component, but the controller is the react-hook-form.

    You can have two options here:

    1. Add the autoSelect, so even when the user lose focus on the input - the current value will be the value of the autocomplete.
    2. Require the user to hit enter in order to save the value that he currently have. (You can use the clearOnBlur option for that).

    Here is the implementation of the first option:

    <Autocomplete
      id="autocomplete"
      freeSolo
      autoSelect
      options={["option1", "option2", "another option"]}
      renderInput={params => (
        <TextField
          {...params}
          label="freeSolo"
          margin="normal"
          variant="outlined"
        />
      )}
    />
    

    And a working example (based on your codesandbox): https://codesandbox.io/s/autocomplete-freesolo-with-auto-value-on-blur-e2smn?file=/demo.js