0

I have a chat application and I'm trying to scroll to bottom when a new message is send, but I have a problem when I try to upload image. I think app scroll immediately before image is loaded and so still in the middle of the image. Here is my AlwaysScrollToBottom component (Which is in another div that is the messages box):

import React, { useEffect, useRef } from "react";

const AlwaysScrollToBottom = () => {
  const elementRef = useRef();
  useEffect(() => {
    return () => {
      elementRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
    };
  });

  return <div ref={elementRef}></div>;
};

export default AlwaysScrollToBottom;

and here is my part of the app that I'm trying to scroll in

 <div className="chat-messages">
 {chats &&
   match.params.id &&
   chats.map((chat) => (
      <MessageBox key={chat._id} chat={chat} user={user} />
   ))}
   <AlwaysScrollToBottom />
 </div>
Simeon Lazarov
  • 109
  • 1
  • 9

1 Answers1

0

I think you cannot use this component for images. Because the image has height 0px at the initial moment. And you have to use the onload callback for image for detecting moment when image was loaded.

You can see here the answer about detecting this moment

Oro
  • 2,250
  • 1
  • 6
  • 22