DEV Community

Cover image for Automatic scrolling for Chat app in 1 line of code + React hook
Deepankar Bhade
Deepankar Bhade

Posted on • Originally published at dpnkr.in

Automatic scrolling for Chat app in 1 line of code + React hook

While using WhatsApp, twitch, or any social media application your chat feed automatically scrolls to the bottom when a new message is sent/received. While building an application with a chat feature this is definitely an important feature you should ship.

If you don't understand what I am actually talking about try out this little demo I made. Type a message and press enter, as you send a new message it goes out of view and you have to scroll to view it.

If you want to try this interactive demo live head over to my original blog post.

Chat before

It's actually pretty simple to fix this, firstly we should know the container element which is wrapping all the chats. Then select the element, get the height using scrollHeight then set the element's vertical scroll height using scrollTop.

That's it.



const el = document.getElementById('chat-feed');
// id of the chat container ---------- ^^^
if (el) {
  el.scrollTop = el.scrollHeight;
}


Enter fullscreen mode Exit fullscreen mode

Here's the new demo with this thing implemented. Now it scrolls to the bottom when a new message comes in.

Chat After

Now coming to the react implementation, we will use useRef & useEffect to get access to the element and handle the side effect.

This would take dep as an argument which will be the dependency for the useEffect and returns a ref which we will pass to the chat container element.



import React from 'react'

function useChatScroll<T>(dep: T): React.MutableRefObject<HTMLDivElement> {
  const ref = React.useRef<HTMLDivElement>();
  React.useEffect(() => {
    if (ref.current) {
      ref.current.scrollTop = ref.current.scrollHeight;
    }
  }, [dep]);
  return ref;
}


Enter fullscreen mode Exit fullscreen mode

Usage of the above hook:



const Chat = () => {
  const [messages , setMessages] = React.useState([])
  const ref = useChatScroll(messages)
  return(
    <div ref={ref} >
      {/* Chat feed here */}
    </div>
  )
}


Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
jamesthomson profile image
James Thomson

Good start 👍 A few more things to consider...

  • How to handle new incoming messages when the user has scrolled up to view old messages
  • Similar to the above point, how to handle loading in chunks of previous messages

Your current implementation will conflict with these use cases

Collapse
 
hanzalahwaheed profile image
Hanzalah Waheed
  1. dev.to/martinez/real-scroll-for-a-...
  2. blog.bitsrc.io/building-a-scrollab...
  3. tuffstuff9.hashnode.dev/intuitive-... For anyone who needs more context, checkout these blogs as well. Found 'em helpful!
Collapse
 
umtdemr profile image
Ümit Demir

Your custom hook is a good point to start. I suggest to avoid scrolling bottom if user scrolled top for reading older messages.

Collapse
 
martinez profile image
Martinez