Romanas
Romanas

Reputation: 645

How to select option by id or by name in Autocomplete Material-UI

I can't find solution how I can select same option by id and by name using Material-UI Autocomplete.

My array of options:

const options = [
   {id: 1, name: 'onion'},
   {id: 2, name: 'potato'},
   {id: 3, name: 'carrot'}
]

What I expect:

This is how my code is looking:

<Autocomplete
   classes={{
      root: classes.root
   }}
   style={{ padding: 0 }}
   options={options}
   getOptionLabel={(option) => option.name}
   renderInput={(params) => (
      <TextField
         {...params}
         required
         className='inputPadding'
         classes={{ root: classes.labelRoot }}
         label={t('mainRank')}
         variant='outlined'
         helperText={positionObjErr && t('required')}
         error={positionObjErr}
      />
   )}
   getOptionSelected={(opt, val) => opt === val}
   value={positionObj}
   onChange={(e, val) => {
      val && setPositionObj(val)
   }}
/>

Upvotes: 0

Views: 2000

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81280

You can override the default filterOptions and make it filters by id after the label filter returns no result:

import TextField from "@material-ui/core/TextField";
import Autocomplete, {
  createFilterOptions
} from "@material-ui/lab/Autocomplete";

const options = [
  { id: 1, name: "onion" },
  { id: 2, name: "potato" },
  { id: 3, name: "carrot" }
];
const _filterOptions = createFilterOptions();
const filterOptions = (options, state) => {
  const result = _filterOptions(options, state);

  if (result.length === 0) {
    return _filterOptions(options, {
      ...state,
      getOptionLabel: (o) => o.id.toString()
    });
  }

  return result;
};

Usage

export default function Filter() {
  return (
    <Autocomplete
      options={options}
      getOptionLabel={(option) => option.name}
      filterOptions={filterOptions}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} variant="outlined" />}
    />
  );
}

Live Demo

Edit 66998083/how-to-select-option-by-id-or-by-name-in-autocomplete-material-ui

Upvotes: 2

Goutham J.M
Goutham J.M

Reputation: 2194

You can put a condition for the prop getOptionSelected like below so it will match for both string and id


<Autocomplete
   classes={{
      root: classes.root
   }}
   style={{ padding: 0 }}
   options={options}
   getOptionLabel={(option) => option.name}
   renderInput={(params) => (
      <TextField
         {...params}
         required
         className='inputPadding'
         classes={{ root: classes.labelRoot }}
         label={t('mainRank')}
         variant='outlined'
         helperText={positionObjErr && t('required')}
         error={positionObjErr}
      />
   )}


   getOptionSelected={(opt, val) => opt.id === Number(val) || opt.name === val}


   value={positionObj}
   onChange={(e, val) => {
      val && setPositionObj(val)
   }}
/>

Upvotes: 0

Related Questions