I am using the Autocomplete component from Material-UI in my React application. When trying to pass a large dataset of approximately 10,000 items as a prop to the Autocomplete component, I am experiencing a significant delay of around 5 seconds before the dropdown menu renders with the expected data.
I have implemented the Autocomplete component following the documentation provided by Material-UI at https://mui.com/material-ui/react-autocomplete/#checkboxes.
Here's the relevant code snippet for reference:
import * as React from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Checkbox from '@mui/material/Checkbox';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import CheckBoxIcon from '@mui/icons-material/CheckBox';
const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;
type AutoSelectDropdownProps = {
dropdownData?: any,
isMultiple?: boolean,
onChange?: any
defaultvalue?: any,
valueField?: string
displayField?: string,
}
export function AutoCompleteDropDown(props: AutoSelectDropdownProps) {
let newObj = [...props.dropdownData];
const loadValues = (event: any, values: any) => {
const target = {
value: [],
name: undefined
};
if (values && values.length > 0) {
target.value = values.map((item: any) => item[props.valueField || 'value']);
}
props.onChange({target});
}
return (
<Autocomplete
multiple
options={newObj}
getOptionLabel={(option) => option.value}
limitTags={2}
onChange={loadValues}
defaultValue={
props.dropdownData.filter((item: any) => {
return props.defaultvalue.includes(item[props.valueField || 'value']);
})
}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
checked={selected}
/>
{option.value}
</li>
)}
size="small"
sx={{ minWidth: 180, width: '100%', mt: 1, backgroundColor: "white" }}
renderInput={(params) => (
<TextField {...params} size='small' />
)}
/>
);
}
export default AutoCompleteDropDown;
You can use custom filters in Material-UI Autocomplete component to limit count of large dataset.
For example:
import Autocomplete, { createFilterOptions } from "@mui/material/Autocomplete";
const filterOptions = createFilterOptions({
ignoreCase: true,
matchFrom: "start",
limit: 10,
});
<Autocomplete
...
filterOptions={filterOptions}
...
/>;
To learn more, see Material-UI-Custom-Filter.
If you have a large amount of data, please see here.