'Why is div.scrollTop = div.scrollHeight off by one message when scrolling?

I am building a messaging app, MERN based. This is pretty straight forward, but when I apply this code to the div, the effect seems to only scroll the messages up to just before the newest message. So when you have the messages all the way scrolled to the bottom, and you send/receive a new message, the new message goes below into the overflow and the scroll doesn't move. The next message after that goes below, and the message from before is pushed into view. So it's always one behind if you don't manual scroll.

Here's the code in question:

 const scrollDiv = document.getElementById('chat-feed-container');

  return selectedConversation.length > 0 ? (
    ((scrollDiv.scrollTop = scrollDiv.scrollHeight),
    (
      <div id='chat-feed' className='col s8 chat-feed'>
        <div id='chat-feed-container'>
          {selectedConversation[0].messages.map((message, i) => (
            <div key={i}>
              <Message message={message} />
            </div>
          ))}
        </div>
      </div>
    ))
  ) : (
    <div className='col s8 chat-feed'>
      <div id='chat-feed-container'>
        <h6>No messages yet!</h6>
      </div>
    </div>
  );

Any reason you can think of this happening?

Here's the repo in case you want a closer look, and this code is from the messages component: https://github.com/sszukhent/telegramish



Solution 1:[1]

I know this answer might not be checked since this is a two year old problem but I had the same issue in my Vue.js application. The problem I had and which I would bet you had was timing. Setting "scrollTop" to "scrollHeight" before the new message has been posted and the application has re-rendered. So it will always be off by element.

The fix to my solution was to wait for the rerender before calculating new height ,and that is a function called "nextTick()"

Hopefully this information helps other look into their React, Angular, Vue applications and solve this problem

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joseph-zabaleta