Material-ui <Autocomplete /> getOptionLabel - passing empty string as value

Viewed 31730

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

5 Answers

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

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.

Related