Showing
1 changed file
with
9 additions
and
1 deletions
1 | -import React, { useCallback, useContext, useEffect, useState } from 'react'; | 1 | +import React, { useCallback, useContext, useEffect, useRef, useState } from 'react'; |
2 | import SocketContext from '../../contexts/SocketContext'; | 2 | import SocketContext from '../../contexts/SocketContext'; |
3 | import { MessageType, RawMessage } from '../common/types'; | 3 | import { MessageType, RawMessage } from '../common/types'; |
4 | import { ChatLine } from './ChatLine'; | 4 | import { ChatLine } from './ChatLine'; |
... | @@ -8,6 +8,7 @@ export const Chat: React.FC = () => { | ... | @@ -8,6 +8,7 @@ export const Chat: React.FC = () => { |
8 | const socket = useContext(SocketContext); | 8 | const socket = useContext(SocketContext); |
9 | const [ input, setInput ] = useState(''); | 9 | const [ input, setInput ] = useState(''); |
10 | const [ chatLines, setChatLines ] = useState<ChatData[]>([]); | 10 | const [ chatLines, setChatLines ] = useState<ChatData[]>([]); |
11 | + const messageEndRef = useRef<HTMLDivElement | null>(null); | ||
11 | 12 | ||
12 | useEffect(() => { | 13 | useEffect(() => { |
13 | socket.on(MessageType.ROOM_CHAT, (data: ChatData) => { | 14 | socket.on(MessageType.ROOM_CHAT, (data: ChatData) => { |
... | @@ -19,6 +20,12 @@ export const Chat: React.FC = () => { | ... | @@ -19,6 +20,12 @@ export const Chat: React.FC = () => { |
19 | } | 20 | } |
20 | }, []); | 21 | }, []); |
21 | 22 | ||
23 | + const handleAutoScroll = useCallback(() => { | ||
24 | + messageEndRef.current?.scrollIntoView({ behavior: 'smooth' }); | ||
25 | + }, []); | ||
26 | + | ||
27 | + useEffect(handleAutoScroll, [chatLines]) | ||
28 | + | ||
22 | const handleEnter = useCallback((e: React.KeyboardEvent) => { | 29 | const handleEnter = useCallback((e: React.KeyboardEvent) => { |
23 | if (e.key === 'Enter') { | 30 | if (e.key === 'Enter') { |
24 | setChatLines([...chatLines, { sender: 'me', message: input }]); | 31 | setChatLines([...chatLines, { sender: 'me', message: input }]); |
... | @@ -37,6 +44,7 @@ export const Chat: React.FC = () => { | ... | @@ -37,6 +44,7 @@ export const Chat: React.FC = () => { |
37 | <div className='w-5/12'> | 44 | <div className='w-5/12'> |
38 | <div className='w-full h-80 rounded shadow flex flex-col items-center end'> | 45 | <div className='w-full h-80 rounded shadow flex flex-col items-center end'> |
39 | {chatLines.map((line, i) => (<ChatLine key={16383+i} chatData={line}/>))} | 46 | {chatLines.map((line, i) => (<ChatLine key={16383+i} chatData={line}/>))} |
47 | + <div ref={messageEndRef} /> | ||
40 | </div> | 48 | </div> |
41 | <input className='w-full px-3 py-2 bg-white | 49 | <input className='w-full px-3 py-2 bg-white |
42 | placeholder-gray-400 text-gray-700 text-sm | 50 | placeholder-gray-400 text-gray-700 text-sm | ... | ... |
-
Please register or login to post a comment