Home > Back-end >  how to limit the number of results for autocomplete input / ant.design
how to limit the number of results for autocomplete input / ant.design

Time:10-08

this is the code..

so when ever the system found any match results , it returns all of them , the which is annoying cuz I have 1000 of results in my data

so instead of showing all the matches result to the user , I need to show just the first 5

import { AutoComplete } from 'antd';
const options = [
  {
    value: 'Test 1',
  },
  {
    value: 'Test 2',
  },
  {
    value: 'Test 3',
  },
  {
    value: 'Test 4',
  },
  {
    value: 'Test 5',
  },
  {
    value: 'Test 6',
  },
  {
    value: 'Test 7',
  },
  {
    value: 'Test 8',
  },
  {
    value: 'Test 9',
  },
  {
    value: 'Test 10',
  }
];

const Complete = () => (
  <AutoComplete
    style={{
      width: 200,
    }}
    options={options}
    placeholder="try to type `b`"
    filterOption={(inputValue, option) =>
      option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
    }
  />
);

ReactDOM.render(<Complete />, mountNode);

I took it from here , and the don't have any thing to prevent that to happen in their api https://ant.design/components/auto-complete/#components-auto-complete-demo-non-case-sensitive

CodePudding user response:

Not sure how to do this in antd specifically, but you can always manually filter the list for the autocomplete.

Example:

function FilterMatch(searchTerm) {
    return (option, index, array) => 
        option.value.toUpperCase().indexOf(searchTerm.toUpperCase()) !== -1;
}

// setup
var [searchTerm, setSearchTerm] = useState('');
var filteredOptions = options.filter(FilterMatch(searchTerm))
                             .filter((_, index) => index < 5);

...

// usage
<Autocomplete options={filteredOptions} onSearch={(text) => setSearchTerm(text)} />

caveat: even if the search term is found within the options list, it may not show up unless typed out explicitly or it's in the first 5 results (of this example).

in this case you'll have to change the filter algorithm to use RegEx for better matching and then you can do your pruning of results.

  • Related