Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material Autocomplete only filtering with getOptionLabel field

currently working with Google material-UI autocomplete component. it is only filtering on the "getOptionLabel" option field when I type something on the input field. however, I want the autocomplete to filter on more than one field. as per doc, I can use CreateFilterOptions to add one more field or use match-sorter to make it work.

https://material-ui.com/components/autocomplete/#createfilteroptions-config-filteroptions

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

<Autocomplete filterOptions={filterOptions} />

at stringify, I am wondering if I could return the whole object instead of just an option.title

please correct me if I am doing something wrong.

like image 606
dev0864 Avatar asked Apr 17 '20 15:04

dev0864


1 Answers

First, multi-additional-filter seems currently not supported by createFilterOptions.

  • source of Material-UI Autocomplete createFilterOptions
const filteredOptions = options.filter(option => {
  let candidate = (stringify || getOptionLabel)(option);
  if (ignoreCase) {
    candidate = candidate.toLowerCase();
  }
  if (ignoreAccents) {
    candidate = stripDiacritics(candidate);
  }
  return matchFrom === "start"
    ? candidate.indexOf(input) === 0
    : candidate.indexOf(input) > -1;
});

We can see it actually filter the options via attributes, which is coded as only accepting one to compare.


Solution

As a workaround, if we don't need matchFrom: 'start', we can simply go through it via bind the two string. Notice it does have potential bugs.

const filterOptions = createFilterOptions({
  // matchFrom: 'start',
  stringify: (option) => option.title + option.text, // make it one for it
});

Try it online: https://stackblitz.com/edit/gwmqss


We can also write our own createFilterOptions function for Autocomplete props getOptionLabel which can support multi-additional-filter with those props like matchFrom: 'start'.

  • document of MUI Autocomplete props API

If you think it's a valuable feature, you can start an issue, too.

  • new issue for MUI feature
like image 87
keikai Avatar answered Sep 20 '22 04:09

keikai