Overnap

채팅 오토스크롤링 추가

import React, { useCallback, useContext, useEffect, useState } from 'react';
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import SocketContext from '../../contexts/SocketContext';
import { MessageType, RawMessage } from '../common/types';
import { ChatLine } from './ChatLine';
......@@ -8,6 +8,7 @@ export const Chat: React.FC = () => {
const socket = useContext(SocketContext);
const [ input, setInput ] = useState('');
const [ chatLines, setChatLines ] = useState<ChatData[]>([]);
const messageEndRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
socket.on(MessageType.ROOM_CHAT, (data: ChatData) => {
......@@ -19,6 +20,12 @@ export const Chat: React.FC = () => {
}
}, []);
const handleAutoScroll = useCallback(() => {
messageEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, []);
useEffect(handleAutoScroll, [chatLines])
const handleEnter = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
setChatLines([...chatLines, { sender: 'me', message: input }]);
......@@ -37,6 +44,7 @@ export const Chat: React.FC = () => {
<div className='w-5/12'>
<div className='w-full h-80 rounded shadow flex flex-col items-center end'>
{chatLines.map((line, i) => (<ChatLine key={16383+i} chatData={line}/>))}
<div ref={messageEndRef} />
</div>
<input className='w-full px-3 py-2 bg-white
placeholder-gray-400 text-gray-700 text-sm
......