I've encountered a problem with displaying the last message in my pet chat application. Currently, I have to manually scroll to the bottom every time I open the chat in order to see the latest message. This scrolling behavior is not very user-friendly and I'm looking for a better solution.
'use client';
import '@styles/chat-messages.scss';
import ChatMessage from '@components/chat-message';
import Spinner from '@components/spinner';
import { LoadingContext } from '@components/providers/LoadingProvider';
import { useRef, useLayoutEffect, useState, useContext } from 'react';
export default function ChatMessages() {
const [loading, setLoadingMessages] = useState(true);
let messages = Array.from({ length: 10 }).reverse();
const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};
useLayoutEffect(() => {
scrollToBottom();
setLoadingMessages(false);
}, [messages]);
return (
<div className='chat-messages'>
{
!loading &&
(
messages.map((_, index) => (
<ChatMessage key={index} i={index} />
))
)
}
{
loading && (
<Spinner />
)
}
<div ref={messagesEndRef} className='chat-messages__point'></div>
</div>
);
}
Currently, the chat starts from the top and then scrolls down as shown here: https://i.sstatic.net/QCgxG2nZ.png However, I would like it to display like this when opening the page: https://i.sstatic.net/Aned1h8J.png
If you'd like, you can sign in with Google (). The site uses simple oauth authentication. I've tried using the loading state but it hasn't resolved the issue. Is there a React hook that runs before the content is displayed?