I've been looking at the (/) API for the autoplete ponent 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?
I've been looking at the (https://material-ui./api/autoplete/) API for the autoplete ponent 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?
Share Improve this question edited Aug 28, 2020 at 4:09 hgb123 14.9k3 gold badges23 silver badges43 bronze badges asked Aug 28, 2020 at 3:53 ph-quiettph-quiett 5412 gold badges7 silver badges21 bronze badges 1- Are you mapping the list from array?? – SM1105922 Commented Aug 28, 2020 at 4:51
3 Answers
Reset to default 11This can be done using filterOptions
prop and createFilterOptions
function.
...
import { Autoplete, 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 (
<Autoplete
filterOptions={filterOptions}
id="bo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
}
GitHub issue
I started with bertida's answer but then I found out createFilterOptions
can do it already (see https://material-ui./ponents/autoplete/#createfilteroptions-config-filteroptions for other interesting options)
const OPTIONS_LIMIT = 10;
const filterOptions = createFilterOptions({
limit: OPTIONS_LIMIT
});
function ComboBox() {
return (
<Autoplete
filterOptions={filterOptions}
id="bo-box-demo"
options={top100Films}
getOptionLabel={(option) => option.title}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);
}
See codesandbox example
Ciao, you could use filterOptions
as explained by @bertdida or you could directly filter options
array in this way:
const ELEMENT_TO_SHOW = 10;
...
<Autoplete
id="bo-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.