Golam Wasy Arnob
Golam Wasy Arnob

Reputation: 117

Hide an option from material-ui autocomplete

I have an autocomplete combo box for field type as follows:

enter image description here

The partial code for the above autocomplete is as follows:

const fieldTypeList = [
  { fieldType: '' },
  { fieldType: 'string' },
  { fieldType: 'long' },
  { fieldType: 'double' },
  { fieldType: 'enum' },
]

class Field  extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      fieldTypeValue: ''
    }
  }
  ...
  ...
render() {
return (
 ...
 ...
 <Autocomplete
     id="disable-clearable"
     style={{ witdth: 200 }}
     options={fieldTypeList}
     getOptionLabel={(option) => option.fieldType}
     onChange={this.onTagsChange}
     value={{ fieldType: fieldTypeValue }}
     getOptionSelected={(option, value) => value.fieldType === option.fieldType}
     disableClearable
     renderInput={(params) =>
        <TextField {...params} label="Field Type" margin="normal" />
       } 
   />
  ...
  ...
  )
 }
}

Now as you can see in the image there is an empty option because I have a "fieldType: ''" like this. I need that field because this form works for creating a new field data and also edit an existing field data. So, if it's a new field data then the value in the autocomplete works like this "fieldType: ''" as in the state the fieldTypeValue is set to "''". But if it's an existing field then I update the state of the fieldTypeValue value after fetching data from api.

However if I remove that empty field type from fieldTypeList then I got warning from getOptionSelected because then '' will not be a matching option as my default fieldTypeValue is set to ''

My question is how can I hide that empty option from that combo box

Upvotes: 1

Views: 5370

Answers (2)

A.Vincent
A.Vincent

Reputation: 267

here is my solution to continue sorting and filtering the option.

filterOptions={(options, state) =>
        options.filter(
          (opt) =>
            opt.fieldType !== "" &&
            opt.fieldType.toLowerCase().includes(state.inputValue.toLowerCase())
        )
      }

Upvotes: 1

badarria
badarria

Reputation: 46

I had the same problem, here is the solution

filterOptions={fieldTypeList => fieldTypeList.filter(opt => opt.fieldType)}

Upvotes: 3

Related Questions