Autocomplete – How can I set a default value?

I tried all the above solutions and nothing worked. Perhaps the API has changed since then.

I finally figured out a solution. It’s not so elegant, but in principle it makes sense. In my case the options are objects. I just had to set the “value” prop using the exact item from my options array. This way componentDidMount and getOptionSelected aren’t needed.

Autocomplete is wrapped inside another component in our case. This is the main code:

class CTAutoComplete extends React.PureComponent {

  getSelectedItem(){
    const item = this.props.options.find((opt)=>{
      if (opt.value == this.props.selectedValue)
        return opt;
    })
    return item || {};
  }

  render() {
    return (
        <Autocomplete
            id={this.props.id}
            className={this.props.className}
            style={{ width: '100%' }}
            options={this.props.options}
            getOptionLabel={this.props.getOptionLabel}
            renderInput={params => (
                <TextField {...params} label={this.props.label} variant="outlined" />
            )}
            onChange={this.props.onChange}
            value={this.getSelectedItem()}
        />
    );
  }
}

IMPORTANT: When setting “value”, you have to make sure to put the null case ” || {} “, otherwise React complains you are changing from an uncontrolled to controlled component.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)