Chat App Development
In my current project, I am developing a chat application using React. The app consists of a list (ul element) that displays messages through individual items (li elements). However, I have encountered an issue where the ul element starts overflowing its container.
Challenge Faced
The main challenge arises when users switch between different chats. Ideally, I would like the ul element to display the overflowed li elements from the bottom instead of starting from the top. This way, users won't have to scroll all the way down to see the latest messages, providing a better user experience.
I attempted to use the scrollIntoView() method to automatically scroll to the last message whenever a new one is added. While this solution works within the same chat screen, switching chats causes the ul element of the new conversation to scroll instantly to the end. My goal is to show the messages from the bottom without any visible scrolling.
Sample Code
const MessagingScreen = ({ openChat }) => {
const messagesEnd = useRef();
const [message, setMessage] = useState("");
const scrollToBottom = () => {
if (openChat.messages.length > 0) {
messagesEnd.current.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
useEffect(() => {
scrollToBottom();
}, [openChat.messages])
return (
<main className="flex flex-column flex-grow mh-50">
<ul className="chat-msgs flex-grow w-100 h-100 bg-white overflow-y-scroll instant">
{openChat.messages.map(chatMessageDetails =>
<ChatMessageItem {...chatMessageDetails} key={chatMessageDetails.message}/>)
}
<div ref={messagesEnd}/>
</ul>
</main>
)
}