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

Deepankar Bhade /

2 min read--

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.

Live demo
Hello World
Deepankar here
This is a simple chat demo
Try typing a message
The new message should ideally scroll down
But it doesnt :(

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.

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

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

Live demo
Hello World
Deepankar here again
This is the fixed chat demo
Try typing a message
On new message the chat feed would scroll down
Nice

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.

useChatScroll.tsx
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; }

Usage of the above hook:

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

Read more: