Material-ui <Autocomplete /> getOptionLabel - passing empty string as value
Solution 1
I got the same error. And, the following worked for me.
getOptionLabel={(option) => option.name || ""}
Solution 2
Your default value is an array with an empty string [""]
which when evaluated in the ternary will return true, thus trying to access the property option.name
that is undefined. You need either to test for that or initialise the state with an empty string which is a falsy value in JS.
Solution 3
I faced a similar problem and I had options as an array of strings. Eg: ["delhi", "new york", "mumbai"]
. I fixed it by adding a check, if the option is a string, if not use an empty string.
getOptionLabel={(option) => typeof option === 'string'
|| option instanceof String ? option : ""}
Related videos on Youtube
Borislav Stefanov
Updated on June 04, 2022Comments
-
Borislav Stefanov almost 2 years
I am using material-ui autocomplete. I am passing to its property options some array of states. The problem I face is with getOptionLabel:
Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string for [""].
I have 2 components. The child one is:
const StateSelect = (props) => { const classes = useStyles(); const handlePick = (e, v) => { props.setState(v); }; return ( <Autocomplete className={classes.inputStyle} options={states} getOptionLabel={(option) => (option ? option.name : "")} onChange={handlePick} value={props.state} renderInput={(params) => ( <TextField {...params} label="State" variant="outlined" /> )} /> ); };
And in the parent one I invoke this child component:
<StateSelect state={selectedState} setState={(state) => setSelectedState(state)} />
In the parent one I have the React hook that controls value of the StateSelect:
const [selectedState, setSelectedState] = useState([""]);
So when I initially pass selectedState as prop to StateSelect it is [''] and I am getting this error message. How could I pass empty value as initial and not to get this error?
I uploaded simple version of my code:
https://codesandbox.io/s/smoosh-field-j2o1p?file=/src/inputStates/input.js