Reputation: 645
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:
3
I get option carrot
carrot
I get same option carrot
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
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;
};
export default function Filter() {
return (
<Autocomplete
options={options}
getOptionLabel={(option) => option.name}
filterOptions={filterOptions}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} variant="outlined" />}
/>
);
}
Upvotes: 2
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