Categories
React Answers

How to Detect When a User Scrolls to Bottom of div with React?

Spread the love

Sometimes, we want to detect when a user scrolls to bottom of div with React.

In this article, we’ll look at how to detect when a user scrolls to bottom of div with React.

Detect When a User Scrolls to Bottom of div with React

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const listInnerRef = useRef();

  const onScroll = () => {
    if (listInnerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = listInnerRef.current;
      if (scrollTop + clientHeight === scrollHeight) {
        console.log("reached bottom");
      }
    }
  };

  return (
    <div>
      <div
        onScroll={onScroll}
        ref={listInnerRef}
        style={{ height: "200px", overflowY: "auto" }}
      >
        {Array(200)
          .fill()
          .map((_, i) => {
            return <p key={i}>{i}</p>;
          })}
      </div>
    </div>
  );
}

We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.

Then we define the onScroll function that destructures the scrollTop, clientHeight and scrollHeight properties from the scrollable div.

The scrollable div element is stored in listInnerRef.current since we assigned the ref to it.

Then we add an if statement to compare scrollTop + clientHeight to scollHeight.

We make the div scrollable by setting it to a fixed height and set overflowY to 'auto'.

And we set the onScroll prop to onScroll so the onScroll function runs when we scroll the scrollable div.

If they’re the same, then we know we reached the bottom.

Therefore, if we scroll to the bottom of the scrollable div, we should see 'reached bottom' logged.

Conclusion

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *