How to avoid scrollbar staying on top when loading more data (infinite scroll) in React

Viewed 109

I'm making an infinite scroll up of the chat room, judging to see the last message and loading the data, but the scrollbar remains at the top of the page, you know, it will automatically execute the call api infinitely,how to keep the scrollbar at the previous message in the position

1 Answers

If you have a reference of the new element that is added, you can use element.scrollIntoView() to make sure it's visible after rendering.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

But: In chat-rooms, this may not always be the right thing to do, as the user may have scrolled up to copy/paste something, and losing the position would be annoying. So check if the chat was already on the bottom before you scroll via JS.

You can take a look at how twitch-chat works to get a good example. The user gets an info if there are new chat messages.

Related