Vipul Prakash
Vipul Prakash

Reputation: 91

How to search based on multiple criteria in AutoComplete API in material UI

I have created a search box using the auto complete API. But it is only searching based on the title field from options and not searching the inputs on other fields.

If the object for example looks like this:

const top100Films = [
  { title: 'The Shawshank Redemption', year: 1994, abc: 'hello1', xyz: 'The nvm1' },
  { title: 'The Godfather', year: 1972, abc: 'hello2', xyz: 'Shaw' },
  { title: 'The Godfather: Part II', year: 1974,  abc: 'hello3', xyz: 'Part nvm3' },
];

so If I enter in the search field 'Shaw' or 'The' then it should search the input text among all the fields like title, abc, xyz keys and not only title

I stumbled upon filter options:

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

export default function Filter() {
  return (
    <Autocomplete
      id="filter-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title}
      filterOptions={filterOptions}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Custom filter" variant="outlined" />}
    />
  );
}

But I don't know how to incorporate multiple fields searching from the input text in filter options.

Upvotes: 0

Views: 1036

Answers (2)

nikitabarnawal
nikitabarnawal

Reputation: 52

Add stringify to options will solve your problem

getOptionLabel: (option) => JSON.stringify(option),

Upvotes: 1

Hari Kishore
Hari Kishore

Reputation: 2870

You just have to alter filter options,

const filterOptions = createFilterOptions({
 // remove this line here
  stringify: (option) => JSON.stringify(option),
});

comment if this doesnt help,

Upvotes: 1

Related Questions