Reputation: 541
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?
Upvotes: 4
Views: 11540
Reputation: 521
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" />
)}
/>
);
}
Upvotes: 2
Reputation: 11166
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.
Upvotes: -1
Reputation: 5298
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" />
)}
/>
);
}
Upvotes: 11