Is there a way to use MUI Autocomplete when the search string is not in the option label?

Viewed 2022

I have an array of objects which are being used in a Material UI Autocomplete and being displayed as options via 'getOptionLabel'. Is there any way to filter the options by matching up the input string with a property of the option value which is not being displayed as the label? For example, in the following sample code snippet, I would like the user to be able to type an item id - e.g. 5141 and that the options should be filtered to 'brass pipes'.

const MyAutoComplete = () => {
    const [item, setItem] = useState()
    const [input, setInput] = useState('')

    const items = [
    { id: 5141, name: 'brass pipes', listPrice: 2.32 }, 
    { id: 214, name: 'bronze pipes', listPrice: 1.89 },
    { id: 3155, name: 'toilet seat ', listPrice: 5.61 }
    ]
    
    return (
        <Autocomplete
            options={items}
            getOptionLabel={(item) => item.name || ''}
            value={item}
            onInputChange={(e, v) => {
                setInput(v)
            }}
            isOptionEqualToValue={(option, value) => option.id === value.id}
            inputValue={input}
            onSelect={(e, v) => setItem(v)}
            renderInput={(params) => (
                <TextField {...params} label="items" variant="standard" />
            )}
        />
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

1 Answers

I think createFilterOptions is the right way to do this. Modifying stringify option makes what you want.

const filterOptions = createFilterOptions({
  stringify: (option) => option.name + option.id,
});

<Autocomplete filterOptions={filterOptions} />;

This is codesandbox link.

Related