I am working on a chat application that uses the List component from react-virtualized to display the chat messages. The list is initially loaded with a fixed number of messages, and new messages are added to the top of the list as the user scrolls up to load more history.
When I add new items to the top of the list, the scroll position is not maintained and the list jumps to the bottom. I have tried using cache.clearAll() to reset the row heights and listRef.current.scrollToPosition() to set the scroll position manually, but it doesn't seem to work as expected.
I am wondering if I should use the InfiniteScroll component instead to handle the loading of new items and maintain the scroll position. Or is there a way to maintain the scroll position when adding new items to the top of the List component without causing a lag in the scrolling experience for the user?
Here is my current code for loading new items and adjusting the scroll position manually:
const handleLoadMore = useCallback(async () => {
try {
const newMessages = await loadNewMessages();
setMessages((prevMessages) => [...newMessages, ...prevMessages]);
// Wait for row heights to be recalculated before setting the new scroll position
setTimeout(() => {
const scrollTop = listRef.current.getScrollTop();
const newScrollTop = scrollTop + newMessages.length * cache.current.defaultHeight;
listRef.current.scrollToPosition(newScrollTop);
}, 0);
} catch (error) {
console.error(error);
}
}, [messages]);