1

// Hi i am a creating a simple chat Application. In this component ,I am Showing All the messages between users .Everything is working as expected .Now i want when a user receives or sends new message i want it should auto scroll to the last message. Now I want to add this feature

import React from "react";
import { Link } from "react-router-dom";
import { useSelector } from "react-redux";
function ShowMessages() {
  const currentUserName = useSelector(
    (state) => state.user.currentUser.username
  );
  const allmessages = useSelector((state) => state.message.allMessage);
  const chatWith = useSelector((state) => state.user.chatWith);
  const LoggedInUser = currentUserName && currentUserName.split("@")[0];

  return (
    <>
      {allmessages &&
        allmessages
          .filter((item) => {
            console.log("item", item.from, item.to, chatWith.id);
            return item.fromto === chatWith.id;
          })
          .map((item, idx) => (
            <li
              className={item.direction === "send" ? "replies" : "sent"}
              key={idx}
            >
              <div className="media">
                   <h5>
                     {item.messageBody}
                      </h5>
                  </div>
                 </li>
          ))}
    </>
  );
}

export default ShowMessages;

1 Answers1

0

Right now you have a component ShowMessages, which renders messages, but in your snippet i can't see any container (perhaps you have it a different component). What i would do is put a ref (by using "useRef") on the container, which holds all of the messages. And every time any message is added (this could be tracked via useEffect), you can get access to the container via the ref (don't forget to use .current). Then, you can choose how to scroll down from this thread - Scroll to bottom of div? First answer should work just fine. Just remember, that you get the element by the ref!

fennyflop
  • 44
  • 2