Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI Autocomplete - Search only from the beginning of the word

I'm using material UI Autocomplete field in my React application and I want the search in it to work only from the beginning of the keyword (for some fields of the objects):

For example, if the options are

[
  {data1:'abc', data2:'a123'},
  {data1:'cba', data2:'345'},
  {data1:'bca3', data2:'654'}
]

and I type a - only the first option should appear. If I type 3 - only the second option should appear.

like image 437
Anna Avatar asked Sep 19 '25 15:09

Anna


2 Answers

I'd like to add some extra infos about filtering. You can also use the createFilterOptions provided from the MUI Autocomplete.

Example:

import { createFilterOptions } from '@material-ui/lab/Autocomplete';

const filterOptions = createFilterOptions({
  matchFrom: 'start',
  stringify: option => option.title,
});

<Autocomplete filterOptions={filterOptions} />

You can set some optional filters:

  • ignoreAccents (Boolean [optional])
  • ignoreCase (Boolean [optional])
  • limit (Number [optional])
  • matchFrom ('any' | 'start' [optional])
  • stringify (Func [optional])
  • trim (Boolean [optional])

https://material-ui.com/components/autocomplete/

Hope this could help someone!

like image 180
Flavio Del Grosso Avatar answered Sep 21 '25 06:09

Flavio Del Grosso


Made it work with filterOptions Autocomplete prop and 'match-sorter' library:

const filterOptions = (options,{ inputValue }) =>
    matchSorter(options, inputValue, {
      keys: [
        { threshold: matchSorter.rankings.STARTS_WITH, key: 'data1' },
        { threshold: matchSorter.rankings.STARTS_WITH, key: 'data2' },
        'data3',
      ],
    });
like image 43
Anna Avatar answered Sep 21 '25 07:09

Anna