Material UI Autocomplete default value of empty string
you can use null
as initial state and that might achieve what you're trying
value={data.value || null}
if you set it to undefined it complains about controlled component, this way I don't get an error even after I use the Autocomplete
I solved it handling the case in which the input string is empty (you are not doing that). 3 things are needed in your Sandbox:
- line 17, inside the
getOptionSelected
, you must return true when the value is the empty string; in this way React selects one option and the warning disappears. - line 14, modify the
getOptionLabel
, handling the case of the empty string. I would do the following:
getOptionLabel={option => option.title ? option.title : ''}
So in case the option has a title, it returns a title, otherwise it returns an empty string that is visualized.
- Finally, modify the
onChange
to handle the empty string, in this way
onChange={(e, selectedObject) => {
if (selectedObject !== null)
setValue(selectedObject)
}}
Overall:
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
export default function FreeSoloCreateOption() {
const [value, setValue] = React.useState("");
return (
<Autocomplete
value={value}
id="empty-string-demo"
options={top100Films}
getOptionLabel={option => option.title ? option.title : ''}
getOptionSelected={(option, value) => {
//nothing that is put in here will cause the warning to go away
if (value === "") {
return true;
} else if (value === option) {
return true;
}
}}
onChange={(e, selectedObject) => {
if (selectedObject !== null)
setValue(selectedObject)
}}
renderOption={option => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField
{...params}
label="Default Value of Empty String"
variant="outlined"
/>
)}
/>
);
}