Spaces:
Sleeping
Sleeping
Update client/src/Chat.jsx
Browse files- client/src/Chat.jsx +14 -7
client/src/Chat.jsx
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
-
import React, { useEffect, useState } from 'react';
|
| 2 |
|
| 3 |
export default function Chat({ socket, roomId, name }) {
|
| 4 |
const [messages, setMessages] = useState([]);
|
| 5 |
const [text, setText] = useState('');
|
|
|
|
| 6 |
|
| 7 |
useEffect(() => {
|
| 8 |
const onMsg = (m) => setMessages((prev) => [...prev, m]);
|
|
@@ -12,6 +13,10 @@ export default function Chat({ socket, roomId, name }) {
|
|
| 12 |
return () => { socket.off('chat_message', onMsg); socket.off('system', onSys); };
|
| 13 |
}, [socket]);
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
const send = () => {
|
| 16 |
if (!text.trim()) return;
|
| 17 |
const m = { name, text, at: Date.now() };
|
|
@@ -21,15 +26,17 @@ export default function Chat({ socket, roomId, name }) {
|
|
| 21 |
};
|
| 22 |
|
| 23 |
return (
|
| 24 |
-
<div
|
| 25 |
-
<div
|
| 26 |
{messages.map((m, i) => (
|
| 27 |
-
<div key={i}
|
|
|
|
|
|
|
| 28 |
))}
|
| 29 |
</div>
|
| 30 |
-
<div
|
| 31 |
-
<input value={text} onChange={e => setText(e.target.value)} placeholder="Type a message"
|
| 32 |
-
<button onClick={send}>Send</button>
|
| 33 |
</div>
|
| 34 |
</div>
|
| 35 |
);
|
|
|
|
| 1 |
+
import React, { useEffect, useRef, useState } from 'react';
|
| 2 |
|
| 3 |
export default function Chat({ socket, roomId, name }) {
|
| 4 |
const [messages, setMessages] = useState([]);
|
| 5 |
const [text, setText] = useState('');
|
| 6 |
+
const logRef = useRef(null);
|
| 7 |
|
| 8 |
useEffect(() => {
|
| 9 |
const onMsg = (m) => setMessages((prev) => [...prev, m]);
|
|
|
|
| 13 |
return () => { socket.off('chat_message', onMsg); socket.off('system', onSys); };
|
| 14 |
}, [socket]);
|
| 15 |
|
| 16 |
+
useEffect(() => {
|
| 17 |
+
if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
|
| 18 |
+
}, [messages]);
|
| 19 |
+
|
| 20 |
const send = () => {
|
| 21 |
if (!text.trim()) return;
|
| 22 |
const m = { name, text, at: Date.now() };
|
|
|
|
| 26 |
};
|
| 27 |
|
| 28 |
return (
|
| 29 |
+
<div className="chat">
|
| 30 |
+
<div ref={logRef} className="chat-log">
|
| 31 |
{messages.map((m, i) => (
|
| 32 |
+
<div key={i} style={{ marginBottom:6 }}>
|
| 33 |
+
<b style={{ color:'var(--accent-2)' }}>{m.name}:</b> {m.text}
|
| 34 |
+
</div>
|
| 35 |
))}
|
| 36 |
</div>
|
| 37 |
+
<div className="chat-input">
|
| 38 |
+
<input className="input" value={text} onChange={e => setText(e.target.value)} placeholder="Type a message" />
|
| 39 |
+
<button className="btn primary" onClick={send}>Send</button>
|
| 40 |
</div>
|
| 41 |
</div>
|
| 42 |
);
|