Auto Scroll is not working in react even after adding eventListener

159 views Asked by At

I am trying to create a chat application, whenever a new message is sent, so it should auto scroll..

But it's not working for me. I have added an event listener to chatBox, i did console.log inside the event callback even it was not working..

I also tried like before event listener, console.log(chatBox.container) i was getting the div in the console

Here's Code :

basically, i have tried this but it's not auto scrolling

const chatBox = useRef(null); // stores the refrence of any component inside a variable
useEffect(() => {
    console.log(chatBox.current);
    chatBox.current.addEventListener("DOMNodeInserted", (event) => {
      const { currentTarget: target } = event;
      target.scroll({ top: target.scrollHeight, behavior: "smooth" });
    });
  }, [chatMessages]);

my div :

 <div className="chat-container-header-btn" ref={chatBox}>
          <MoreVertIcon />
        </div>

I tried this as well from an articl :

const scrollToBottom = () => {
    chatBox.current?.scrollIntoView({
      behavior: "smooth",
      block: "end",
      inline: "nearest",
    });
  };
  useEffect(() => {
    scrollToBottom();
  }, [chatMessages]);

1

There are 1 answers

0
Daniel Santana On

I tried many ways and this is the only one that managed to auto-scroll a div as its content expands:

Step 1: Import the necessary references

   import { useEffect, useRef } from "react";

Step 2: Inside your function component, declare your ref constant

   const refDivAfterMessages = useRef<HTMLDivElement>(null);

Step 3: Inside your div container, and after its content, add a new DIV and add to it the ref you declared in the previous step:

   <div ref={refDivAfterMessages} />

Step 4: Define your useEffect and set it's DependencyList to your list length, using the scrollIntoView to give the scroll attributes:

  useEffect(() => {
    if (props.messages.length) {
      refDivAfterMessages.current?.scrollIntoView({
        behavior: "smooth",
        block: "end",
      });
    }
  }, [props.messages.length]);

Credits to Source: https://reacthustle.com/blog/react-auto-scroll-to-bottom-tutorial