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
I got the same error. And, the following worked for me.
getOptionLabel={(option) => option.name || ""}
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 : ""}
I solved this problem by just setting values like this.
getOptionLabel={(option)=>(option.name?option.name:'')}
value={props.state || null}
this worked for me in material UI version 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With