Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 368
Borislav Stefanov Avatar asked Jul 16 '20 11:07

Borislav Stefanov


4 Answers

I got the same error. And, the following worked for me.

getOptionLabel={(option) => option.name || ""}
like image 149
Vijayanand Settin Avatar answered Oct 13 '22 13:10

Vijayanand Settin


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 : ""}
like image 23
Bikas Katwal Avatar answered Oct 13 '22 13:10

Bikas Katwal


I solved this problem by just setting values like this.

getOptionLabel={(option)=>(option.name?option.name:'')}
like image 3
Waqas Devolper Avatar answered Oct 13 '22 14:10

Waqas Devolper


value={props.state || null} this worked for me in material UI version 4

like image 2
swarna mohn Avatar answered Oct 13 '22 13:10

swarna mohn