Mykyta
Mykyta

Reputation: 396

Material Ui Autocomplete - Filtering options is not working as expected

I have Autocomplete where I pass an array of fetched and predefined options... https://codesandbox.io/s/geocoding-demo-forked-2f189?file=/src/App.js

When I type e.g. "Diestsestraat Leuven" it doesn't display any options, but when I console.log it I see array of options. enter image description here

But then it doesn't filter out predefined options (see screenshot)

enter image description here

Any suggestions?

Upvotes: 12

Views: 26978

Answers (5)

Majid M.
Majid M.

Reputation: 4974

You can use filterOptions prop in Autocomplete component. It gives you two parameters. The first one is the options you've given to it and second one is the state of the input component. So you can customize it with your own filter:

const filterOptions = (options, state) => {
    let newOptions = [];
    options.forEach((element) => {
      if (
        element.place_name
          .replace(",", "")
          .toLowerCase()
          .includes(state.inputValue.toLowerCase())
      )
        newOptions.push(element);
    });
    return newOptions;
  };

Edit geocoding-demo (forked)

Upvotes: 5

Mehdi Torabi
Mehdi Torabi

Reputation: 11

I had an issue fetching data from the server and couldn't see the exact options. (I was calling API for a filter list of users and showing in autocomplete) after all I just added an option based on mui documentation.

filterOptions={(x) => x}

it will be mostly useful if your logic is fetching new options on each keystroke and using the current value of the textbox to filter on the server, you may want to consider throttling requests.

Upvotes: 0

Dimitir
Dimitir

Reputation: 366

In my case, I tried adding key to renderOption solutions. Reference: here

 <Autocomplete
        ...
          renderOption={(props, item) => (
                  <li {...props} key={item.key}>
                    <ListItemText>{item.label}</ListItemText>
                  </li>
        )
  />

Upvotes: 23

Hashim khan
Hashim khan

Reputation: 29

 renderOption={(props, item) => (
            <li {...props} key={item.key}>
                    {item.name}     
            </li>           
    )}


replace item.name with your render values

Upvotes: 0

Pieter du Buisson
Pieter du Buisson

Reputation: 1

So on the filterOptions you are only returning options where you should be filtering. You could try adding:

filterOptions={(options) =>
  options.filter(({ place_name }) => place_name.includes(query))
}

Upvotes: -1

Related Questions