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

Whereas utilizing WhatsApp, twitch, or any social media utility your chat feed robotically scrolls to the underside when a brand new message is shipped/acquired. Whereas constructing an utility with a chat characteristic that is undoubtedly an necessary characteristic it’s best to ship.

In case you do not perceive what I’m truly speaking about check out this little demo I made. Kind a message and press enter, as you ship a brand new message it goes out of view and it’s a must to scroll to view it.

If you wish to do this interactive demo reside head over to my unique weblog submit.

It is truly fairly easy to repair this, firstly we should always know the container ingredient which is wrapping all of the chats. Then choose the ingredient, get the peak utilizing scrollHeight then set the ingredient’s vertical scroll top utilizing scrollTop.

That is it.

const el = doc.getElementById('chat-feed');
// id of the chat container ---------- ^^^
if (el) {
  el.scrollTop = el.scrollHeight;
Enter fullscreen mode

Exit fullscreen mode

This is the brand new demo with this factor applied. Now it scrolls to the underside when a brand new message is available in.

Chat After

Now coming to the react implementation, we’ll use useRef & useEffect to get entry to the ingredient and deal with the aspect impact.

This could take dep as an argument which would be the dependency for the useEffect and returns a ref which we’ll go to the chat container ingredient.

import React from 'react'

perform useChatScroll<T>(dep: T): React.MutableRefObject<HTMLDivElement> {
  const ref = React.useRef<HTMLDivElement>();
  React.useEffect(() => {
    if (ref.present) {
      ref.present.scrollTop = ref.present.scrollHeight;
  }, [dep]);
  return ref;
Enter fullscreen mode

Exit fullscreen mode

Utilization of the above hook:

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

Exit fullscreen mode

Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.

Checkout extra Articles on Sayed.CYou

#Automated #scrolling #Chat #app #line #code #React #hook