Horrerblade
Horrerblade

Reputation: 168

Setting default value of Material UI Autocomplete

I am trying to set the initial value of the Autocomplete to "ACCU-SEAL 35-532 Bag Sealer" but get the following error:

Material-UI: the 'getOptionLabel' method of Autocomplete returned undefined instead of a string for "ACCU-SEAL 35-532 Bag Sealer".

so I tried to add the following to my Autocomplete:

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

but I get the same error.

I have an example of my code up here: https://codesandbox.io/s/material-demo-fv075?file=/formElementsEdit.jsx

Any help in setting the initial value of the autocomplete would be greatly appriciated.

Upvotes: 1

Views: 4088

Answers (1)

Dekel
Dekel

Reputation: 62556

When you use have options in the Autocomplete, you should use the same values that your options contains.

In your examples each option is an object with value and label. Since you use that label in the getOptionLabel function - you should use at least the label in the object that you are passing.

Option #1:

const value = "ACCU-SEAL 35-532 Bag Sealer";
...
<Autocomplete
    ...
    value={{label: value}}

Option #2:

const value = "ACCU-SEAL 35-532 Bag Sealer";
...
<Autocomplete
    ...
    value={{label: value, value: 1}}

Option #3: ...

In any of the above options - the value of the property value should be an object with at least one key - the label key.

Check the following example based on your code: https://codesandbox.io/s/material-demo-zzfh7?file=/formElementsEdit.jsx

Upvotes: 5

Related Questions