Categories
React Answers

How to detect when user scrolls to bottom of div with React?

Spread the love

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

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

How to detect when user scrolls to bottom of div with React?

To detect when user scrolls to bottom of div with React, we check if the sum of the scrollTop and clientHeight of the scroll container is the same as its scrollHeight.

For instance, we write

import React, { useRef, useEffect } from "react";

const MyListComponent = () => {
  const listInnerRef = useRef();

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

  return (
    <div className="list">
      <div className="list-inner" onScroll={onScroll} ref={listInnerRef}>
        {/* List items */}
      </div>
    </div>
  );
};

to call onScroll when we scroll by setting the onScroll prop of the div to onScroll.

Then we assign a listInnerRef to the div.

In onScroll, we check if the sum of the scrollTop and clientHeight of the scroll container is the same as its scrollHeight.

If it is, then the bottom of the element is reached.

Conclusion

To detect when user scrolls to bottom of div with React, we check if the sum of the scrollTop and clientHeight of the scroll container is the same as its scrollHeight.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.