Search code examples
reactjsautocompletematerial-ui

Autocomplete Material UI search based on two attributes


I have this data:

const sample = [
    {hero: 'DARTH VADER', faction: 'EMPIRE'},
    {hero: 'LUKE SKYWALKER', faction: 'REBEL'},
    {hero: 'GREEDO', faction: 'BOUNTY HUNTER'},
];

Using Autocomplete, I am able to search the value via either hero or faction attribute by assigning one of them in getOptionLabel={(option) => {option.hero}} or getOptionLabel={(option) => {option.faction}} prop.

However I would like to be able to search using both of these attributes at the same time (typing either DARTH VADER or EMPIRE will return the same result).

The questions are as follows:

  1. Can I achieve that using a single autocomplete?
  2. If not, can we use a toggle to change which attribute to look for in the autocomplete?

Many thanks


Solution

  • Autocomplete provides the filterOptions prop.

    you can use it to provide a custom filter like so (here's a codesandbox):

    import React from 'react';
    import TextField from '@material-ui/core/TextField';
    import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete';
    
    const filterOptions = createFilterOptions({
      matchFrom: 'any',
      stringify: (option) => option.hero + option.faction,
    });
    
    export default function Filter() {
      return (
        <Autocomplete
          id="filter-demo"
          options={sample}
          getOptionLabel={(option) => option.hero}
          filterOptions={filterOptions}
          renderInput={(params) => <TextField {...params} label="Custom filter" variant="outlined" />}
        />
      );
    }
    
    const sample = [
      {hero: 'DARTH VADER', faction: 'EMPIRE'},
      {hero: 'LUKE SKYWALKER', faction: 'REBEL'},
      {hero: 'GREEDO', faction: 'BOUNTY HUNTER'},
    ];