DEV Community

Amin Deraiya
Amin Deraiya

Posted on

React detect div reach top and bottom

Detect Div reaches to bottom

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Detect Div reaches to Top

import React, { useRef } from "react";

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

  const onScroll = () => {
    if (listInnerRef.current) {
      const { scrollTop } = listInnerRef.current;
      console.log({ scrollTop });

      if (scrollTop === 0) {
        console.log("reached Top");
      }
    }
  };

  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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)