简体   繁体   中英

limit the number of suggestions AutoComplete component

I've been looking at the ( https://material-ui.com/api/autocomplete/ ) API for the autocomplete component but I can't seem to find a way (from my limited knowledge of javascript) to only display a certain number of options below the TextField.

I'm trying to incorporate a search function with over 7,000 data but I don't want to display all of it at once. How can I limit the options to at most 10 suggestions?

补偿

This can be done using filterOptions prop and createFilterOptions function.

...
import { Autocomplete, createFilterOptions } from "@material-ui/lab";

const OPTIONS_LIMIT = 10;
const defaultFilterOptions = createFilterOptions();

const filterOptions = (options, state) => {
  return defaultFilterOptions(options, state).slice(0, OPTIONS_LIMIT);
};

function ComboBox() {
  return (
    <Autocomplete
      filterOptions={filterOptions}
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

编辑cool-yalow-pd4i6

GitHub issue

Ciao, you could use filterOptions as explained by @bertdida or you could directly filter options array in this way:

const ELEMENT_TO_SHOW = 10;
...
    <Autocomplete
          id="combo-box-demo"
          options={top100Films.filter((el, i) => {  // here add a filter for options
            if (i < ELEMENT_TO_SHOW) return el;
          })}
          getOptionLabel={(option) => option.title}
          style={{ width: 300 }}
          renderInput={(params) => (
            <TextField {...params} label="Combo box" variant="outlined" />
          )}
        />

Here a codesandbox example.

I started with bertida's answer but then I found out createFilterOptions can do it already (see https://material-ui.com/components/autocomplete/#createfilteroptions-config-filteroptions for other interesting options)

const OPTIONS_LIMIT = 10;
const filterOptions = createFilterOptions({
  limit: OPTIONS_LIMIT
});

function ComboBox() {
  return (
    <Autocomplete
      filterOptions={filterOptions}
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={(option) => option.title}
      style={{ width: 300 }}
      renderInput={(params) => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

See codesandbox example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM