How to check if scroll is near the bottom

Viewed 189

I have Dropdown list in my React app: when scrolling on the bottom I'm fetching next elements from backend so my dropdown list is dynamic. I want to know if I'm on the bottom of the list - then I want to fetch next elements. How to check if it's time to fetch next elements?

<Content>
        <MySelectField onClick={handleOnClick} onScroll={handleOnScroll}>
function handleOnScroll(e) {
        const { scrollTop, scrollHeight, offsetHeight } = e.target;
        if (offsetHeight - scrollTop < 50) {
            handleLoadNextElements();
        }
    }

What conditions should I use to fetch next elements when I'm on teh bottom of my scrollable list?

2 Answers

I fixed my problem by adding onScroll to my div:

 <TemplateSelectField
                    onClick={handleOnClick}
                    onScroll={handleOnScroll}
                >

and then:

function handleOnScroll(e) {
        const { scrollTop, scrollHeight, offsetHeight } = e.target;
        const hasScrollReachedBottom =
            offsetHeight + scrollTop > scrollHeight - 40;

        if (hasScrollReachedBottom) {
            handleLoad();
        }
    }

Works excellent:)

Related