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.
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;
}
Here's the new demo with this thing implemented. Now it scrolls to the bottom when a new message comes in.
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;
}
Usage of the above hook:
const Chat = () => {
const [messages , setMessages] = React.useState([])
const ref = useChatScroll(messages)
return(
<div ref={ref} >
{/* Chat feed here */}
</div>
)
}
Top comments (4)
Good start 👍 A few more things to consider...
Your current implementation will conflict with these use cases
Your custom hook is a good point to start. I suggest to avoid scrolling bottom if user scrolled top for reading older messages.
@umtdemr this is the solution dev.to/martinez/real-scroll-for-a-...