I have an issue and couldn’t find any approach to solve it.
I make a pet chat application, and of course, I want to show last message,
but because the last message appears at the end,
so I need to scroll,
but it doesn’t look good when u open chat and see manual scrolling from the first to the last message, any ideas?
In terms of HTML, we have a block that overlaps and we want to show the bottom of the content.
Loading doesn’t help we see scrolling anyway.
'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);
// const {setLoading} = useContext(LoadingContext);
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>
);
}
it starts from the top and then scrolls, I see this behaviour
but I want to have it like this when open the page
If u want u can authorize with google (https://chat-room-chi-seven.vercel.app/), it uses simple oauth
I tried to use the loading state but it doesn’t work, maybe there is a react hook that runs before content is shown
2
Answers
Change the behaviour to auto: messagesEndRef.current?.scrollIntoView({ behavior: 'auto' });
it’s is probably because of The useLayoutEffect hook is running before the messages are fully rendered, causing the scrollToBottom function to execute prematurely. Try this