react-chat-elements icon indicating copy to clipboard operation
react-chat-elements copied to clipboard

Autoscroll

Open aegikian opened this issue 2 years ago • 2 comments

Hi all!

Can you tell me how to implement scrolling when receiving or sending a message? Provided that for me toBottomHeight does not work

aegikian avatar Jan 15 '23 20:01 aegikian

I also had this problem. For me the problem was that I had equipped the parent container with an overflow. If the MessageList itself is not scrollable, it logically does not work. A custom solution could be to add a div block below the list to which you automatically scroll when a new message is added.

MaxNoetzold avatar Feb 06 '23 10:02 MaxNoetzold

Auto-scrolling isn't working for me either, even though I seem to have the structure set-up correctly:

      <div className="messageListContainer">
        <MessageList className='message-list' lockable={false} toBottomHeight={'100%'} dataSource={messages} onScroll={handleScroll} />
      </div>

In my case, messageListContainer does not have an overflow, and I've added a console.log() statement in handleScroll() to confirm that the MessageList itself is scrolling its messages. (And not the whole div.) Looking at the code here:

https://github.com/Detaysoft/react-chat-elements/blob/master/src/MessageList/MessageList.tsx#L26

... it seems that it should auto-scroll when toBottomHeight is set to '100%'.


UPDATE

I found a workaround to automatically scroll the field to the bottom:

  // I'm using Redux, so this is where I extract the messages (state) from the store
  const messages = useAppSelector((state: RootState) => state.chat.messages);

  // Utility function to scroll MessageList to bottom:
  const scrollToBottom = () => {
    const mlistElement = document.getElementsByClassName('rce-mlist')[0];
    if (typeof mlistElement !== 'undefined') {
      mlistElement.scrollTop = mlistElement.scrollHeight;
    }
  }; 

  // Listener for when the state changes:
  useEffect(() => {
    scrollToBottom()
  }, [messages]);

  // Eventually:
  return (
      <div className="messageListContainer">
        <MessageList className='message-list' lockable={false} toBottomHeight={'100%'} dataSource={messages} />
      </div>
  );

antun avatar Jun 17 '23 00:06 antun