Material Ui Autocomplete - Filtering options is not working as expected

Viewed 4070

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?

2 Answers

You can use filterOptions prop in Autocomplete component. It gives you 2 parameter. 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 filterize:

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)

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))
}
Related