'Problem with scrollIntoView not scrolling until the end on React
I have one component that builds a list of messages for a chat, the scrollIntoView
function only works when I open the chat for second time, (the first time, it doesn't scroll until the end). I attached some photos and videos and some code.
const queryClient = useQueryClient()
const { data, isLoading } = useChatMessages(id)
const { socket } = useSocket()
const viewRef = useRef(null)
useEffect(() => {
socket.on('receive_message', (data) => {
queryClient.setQueryData(['CHATMESSAGES', id], function(oldData) {
return [...oldData, data]
})
})
}, [socket])
useEffect(() => {
viewRef.current && viewRef.current.scrollIntoView({behavior: 'smooth', block: 'start'})
}, [data])
if (isLoading) return <span>Loading...</span>
return (
<div className={styles.chatMessages}>
{data.map(message => (
message.sender_id !== 'x' ? <MessageReceived key={message.id} date={message.date} message={message.message} /> : <MessageSended key={message.id} date={message.date} message={message.message} />
))}
<div ref={viewRef} />
</div >
)
}
Video: https://i.imgur.com/p3qqGZn.gif (As you can see, I need to scroll manually until the end) Can someone help me resolving the error?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|