简体   繁体   中英

Detect scrolled to top of div with overflow: scroll in ReactJs

I'm creating a messaging feature. The conversation occupies only 100vh height minus the header - so, I have to make its overflow set to scroll. How do I detect if the user scrolls to the topmost part of the conversation? I will fetch older messages once the user scrolls to the top.

I did some research but none of them are working. I think they're only applicable for a scrollable page.

The code snippet below is similar to what I am seeing over the web. However, the scroll never gets triggered.

const top_ref = React.useRef < HTMLDivElement > null;

const trackScrolling = () => {
  console.log("scrolling");
};

React.useEffect(() => {
  document.addEventListener("scroll", trackScrolling);

  return () => {
    document.removeEventListener("scroll", trackScrolling);
  };
});

As pointed out by cloned , Intersection Observer does the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM