1
votes

I'm working on a chat app and am using the scroller from bottom to top to load older messages. When a new message arrives I want to check first if the user is at the bottom of the div, and only then use a scrollToBottom function. How can I get the current height/position of the user?

https://www.npmjs.com/package/react-infinite-scroller

Thank you, Omri

1

1 Answers

2
votes

Unfortunately it's been a few days without reply. This is my workaround:

I created a boolean called isBottom, and attached onScroll={handleScroll} function to my messages div.

const [isBottom, setIsBottom] = useState(true);

const scrollToBottom = (behavior) => {
messagesEndRef.current.scrollIntoView();
};

const handleScroll = (e) => {
const bottom =
  e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
if (bottom) {
  setIsBottom(true);
} else {
  setIsBottom(false);
  } 
};

The messages div:

      <div className="msg_list" onScroll={handleScroll}>
    <InfiniteScroll
      loadMore={loadMore}
      initialLoad={true}
      hasMore={hasMoreItems}
      loader={<LoadingAnimation key={0} />}
      useWindow={false}
      isReverse={true}
    >
      {messages}
      <div ref={messagesEndRef} />
    </InfiniteScroll>
  </div>

And then I added a useEffect to handle changes from my messages array (arriving from props)

  useEffect(() => {
if (isBottom) {
  scrollToBottom();
} else {
  setUnreadMessages((unreadMessages) => unreadMessages + 1);
 }
}, [messageList]);

* BTW you also need to wire the scrollTobottom function to your send message box, since if you are the one who sent the message it should scrollToBottom anyway