Add “Select All” functionality in MUI Virtualized Autocomplete

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>
                        )
                    }}
                />
            )}
        />
    );
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật