Manzana
Manzana

Reputation: 325

Is there a way to add a loader component to the Material ui Autocomplete component

I'm trying to implement an infinite scroll to my autocomplete component and it looks something like this

const SearchSelect: React.FC<SearchSelectProps> = (props) => {
    return (
        <Autocomplete
            {...props}
            ListboxProps={{
                onScroll: (event: React.SyntheticEvent) => {
                    const listboxNode = event.currentTarget
                    if (
                        listboxNode.scrollTop + listboxNode.clientHeight ===
                        listboxNode.scrollHeight
                    ) {
                        props.loadmoreresults && props.loadmoreresults()
                    }
                },
            }}
            renderInput={(params) => (
                <TextField
                    {...params}
                    label={props.label}
                    variant="filled"
                />
            )}
        />
    )
}

export default withStyles(styles)(SearchSelect)

I would like to add a loader component at the end of the list every time I scroll to the bottom of it. If that is not possible, at least adding a text "Loading" at the end. How would you do it?

Thanks in advance

Upvotes: 3

Views: 2504

Answers (1)

Manzana
Manzana

Reputation: 325

I finally found how to do it using the renderOption prop, as follows:

           renderOption={(option: any) => {
                if (option === props.options[props.options.length - 1] && props.hasNextPage) {
                    return (
                        <div>
                            {option.label}
                            <Loader />
                        </div>
                    )
                }
                return option.label
            }}

EDIT: this will add a loader to the last item, it will not be separated from the last option so it might not be suitable for you if you're looking to add an extra component under the list. To do that, you can create your custom Paper component and add it through the PaperComponent prop:

function CustomPaper({ children, ...others }) {
    return (
        <Paper variant="outlined" {...others}>
            {children}
            <Loader />
        </Paper>
    )
}

Upvotes: 5

Related Questions