Skip to content

Commit

Permalink
fix: cannot auto focus when message update
Browse files Browse the repository at this point in the history
  • Loading branch information
ZL-Asica committed Jan 20, 2025
1 parent a060b8f commit 3af2827
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/components/Chatbot/MessageList.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { Box } from '@mui/material'
import { memo } from 'react'
import { memo, useEffect, useRef } from 'react'

const MessageList = memo(({ messages }: { messages: Message[] }) => {
const lastMessageRef = useRef<HTMLDivElement | null>(null)

useEffect(() => {
if (lastMessageRef.current) {
lastMessageRef.current.scrollIntoView({ behavior: 'smooth' })
}
}, [messages])

return (
<Box
sx={{
Expand All @@ -13,9 +21,10 @@ const MessageList = memo(({ messages }: { messages: Message[] }) => {
gap: 2,
}}
>
{messages.map(({ id, text, sender, timestamp }) => (
{messages.map(({ id, text, sender, timestamp }, index) => (
<Box
key={id}
ref={index === messages.length - 1 ? lastMessageRef : null}
sx={{
alignSelf: sender === 'user' ? 'flex-end' : 'flex-start',
maxWidth: '70%',
Expand Down

0 comments on commit 3af2827

Please sign in to comment.