Anna
Anna

Reputation: 3141

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.

Upvotes: 4

Views: 7428

Answers (3)

Flavio Del Grosso
Flavio Del Grosso

Reputation: 590

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!

Upvotes: 9

Anna
Anna

Reputation: 3141

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',
      ],
    });

Upvotes: 4

Ahmed Gamal Mustafa
Ahmed Gamal Mustafa

Reputation: 29

https://material-ui.com/components/autocomplete/#multiple-values

It works, You need to add multiple

  <Autocomplete
    multiple
    id="tags-standard"
    options={top100Films}
    getOptionLabel={option => option.title}
    defaultValue={[top100Films[13]]}
    renderInput={params => (
      <TextField
        {...params}
        variant="standard"
        label="Multiple values"
        placeholder="Favorites"
      />
    )}
  />

Upvotes: -1

Related Questions