I want to add the “Select All” option in my MUI Autocomplete component but I am finding it difficult to do so because I am using the Virtualized version due to the large size of my options list.
Below is the code of my component. I tried to integrate the following implementation: https://github.com/valerii15298/mui-autocomplete-select-all/blob/main/src/index.tsx but I kept getting the error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `List`.
This was due to me attempting to render a “Select All” checkbox before the rest of the options without adding to the options list.
<div className = "d-flex flex-column">
<Checkbox
indeterminate={indeterminate}
checked={selectedAll}
onChange={(_e) => onSelectAll(selectedAll)}
sx={{ ml: 2 }}
/>
Select All
</div>
{renderRow}
So I tried to render outside the VariableSizeList component but while it did display, it kept closing my dropdown. I believe that was because it was being considered as an outside click.
My attempts on adding the “Select All” option to options list worked to an extent but it was forcing me to make changes in the handleSelectChange function which is sent as a parameter to this component. I want to avoid making changes in all my other parent components where this Autocomplete is being called. Is that possible?
import { Fragment, createContext, forwardRef, useContext, useEffect, useMemo, useRef } from 'react';
import { useTheme, styled } from '@mui/material/styles';
import { VariableSizeList } from 'react-window';
import Autocomplete, { autocompleteClasses } from '@mui/material/Autocomplete';
import useMediaQuery from '@mui/material/useMediaQuery';
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';
import Chip from '@mui/material/Chip';
import Popper from '@mui/material/Popper';
import Typography from '@mui/material/Typography';
import CircularProgress from '@mui/material/CircularProgress';
const icon = <CheckBoxOutlineBlankIcon fontSize = "small" />;
const checkedIcon = <CheckBoxIcon fontSize = "small" />;
function renderRow(props)
{
const { data, index, style } = props;
const dataSet = data[index];
const { key, ...otherProps } = dataSet[0];
const selected = dataSet[2]?.selected || false;
const inlineStyle = { ...style, top: style.top, backgroundColor: (index % 2 === 0) ? '#f0f0f0' : '#ffffff', padding: '0 5px', height: 'fit-content' };
return (
<Typography component = "li" key = {key} {...otherProps} style = {inlineStyle}>
<Checkbox
sx = {{ paddingTop: 0, paddingBottom: 0 }}
icon = {icon}
checkedIcon = {checkedIcon}
checked = {selected}
/>
dataSet[1].value
</Typography>
);
}
const OuterElementContext = createContext({});
const OuterElementType = forwardRef((props, ref) =>
{
const outerProps = useContext(OuterElementContext);
return <div ref = {ref} {...props} {...outerProps} />;
});
function useResetCache(data)
{
const ref = useRef(null);
useEffect(() =>
{
if (ref.current !== null)
{
ref.current.resetAfterIndex(0, true);
}
}, [data]);
return ref;
}
const ListboxComponent = forwardRef(function ListboxComponent(props, ref)
{
const { children, ...other } = props;
const itemData = [];
children.forEach((item) =>
{
itemData.push(item);
itemData.push(...(item.children || []));
});
const theme = useTheme();
const smUp = useMediaQuery(theme.breakpoints.up('xs'), { noSsr: true });
const itemCount = itemData.length;
const itemSize = smUp ? 20 : 30;
const getChildSize = () =>
{
return itemSize;
};
const getHeight = () =>
{
if (itemCount > 8)
{
return 8 * itemSize;
}
return itemData.map(getChildSize).reduce((a, b) => a + b, 0);
};
const gridRef = useResetCache(itemCount);
return (
<div ref = {ref}>
<OuterElementContext.Provider value = {other}>
<VariableSizeList
ref = {gridRef}
itemData = {itemData}
height = {getHeight() + 2}
width = "100%"
outerElementType = {OuterElementType}
innerElementType = "ul"
itemSize = {(index) => getChildSize(itemData[index])}
overscanCount = {5}
itemCount = {itemCount}
>
{renderRow}
</VariableSizeList>
</OuterElementContext.Provider>
</div>
);
});
const StyledPopper = styled(Popper)(
{
[`& .${autocompleteClasses.listbox}`]:
{
boxSizing: 'border-box',
'& ul': {
padding: 0,
margin: 0
}
}
});
export default function VirtualizedAutocomplete({ isLoading = false, filterOn, helperText = "", options, selectedOptions, handleSelectChange })
{
return (
<Autocomplete
size = "small"
sx = {{ width: '100%' }}
title = {filterOn}
freeSolo = {true}
loading = {isLoading}
forcePopupIcon = {true}
autoHighlight = {true}
disableClearable = {true}
disableCloseOnSelect = {true}
multiple = {true}
limitTags = {1}
PopperComponent = {PopperComponent}
ListboxComponent = {ListboxComponent}
options = {options}
value = {selectedOptions}
isOptionEqualToValue = {(option, value) => (option.id === value.id)}
getOptionLabel = {(option) => option?.value ? option.value.toString() : option}
onChange = {(event, newValue) => handleSelectChange(filterOn, newValue)}
renderOption = {(props, option, state) => [props, option, state, state.index]}
renderInput = {(params) => (
<TextField
{ ...params }
sx = {{
'& .MuiInputBase-input': {
overflow: 'hidden',
textOverflow: 'ellipsis'
}
}}
size = "small"
margin = "dense"
helperText = {helperText}
label = {filterOn}
InputProps = {{
...params.InputProps,
endAdornment: (
<Fragment>
{isLoading ? <CircularProgress color = "inherit" size = {20} /> : null}
{params.InputProps.endAdornment}
</Fragment>
)
}}
/>
)}
/>
);
}