|
| 1 | +import { useState } from "react"; |
| 2 | +import { useChat } from "../../context/ChatProvider"; |
| 3 | +import { useUserContext } from "../../context/UserProvider"; |
| 4 | + |
| 5 | +const UserChat = () => { |
| 6 | + const { messages, sendMessage } = useChat(); |
| 7 | + const { user } = useUserContext(); |
| 8 | + const [message, setMessage] = useState<string>(""); |
| 9 | + |
| 10 | + const handleSendMessage = () => { |
| 11 | + if (message.trim()) { |
| 12 | + sendMessage({ username: `${user?.name.fname} ${user?.name.lname}`, message }); |
| 13 | + setMessage(""); |
| 14 | + } |
| 15 | + }; |
| 16 | + |
| 17 | + return ( |
| 18 | + <div className="text-black min-w-56 max-w-full h-full flex flex-col" onKeyDown={(e) => { |
| 19 | + if (e.key === 'Enter') handleSendMessage() |
| 20 | + }}> |
| 21 | + <div className="space-y-2"> |
| 22 | + <p className="text-3xl text-white font-poppins font-thin"> |
| 23 | + Chat |
| 24 | + </p> |
| 25 | + <hr /> |
| 26 | + </div> |
| 27 | + |
| 28 | + <div className="overflow-y-auto flex-grow p-2"> |
| 29 | + <div className="space-y-2"> |
| 30 | + {messages.map((msg, index) => ( |
| 31 | + <div |
| 32 | + key={index} |
| 33 | + className={`text-left text-lg text-white ${msg.username === 'YourUsername' ? 'bg-blue-700 self-message' : 'bg-gray-800 other-message' |
| 34 | + } rounded-md`} |
| 35 | + > |
| 36 | + <div className="flex items-center justify-between"> |
| 37 | + <div className="text-sm font-medium"> |
| 38 | + {msg.username} |
| 39 | + </div> |
| 40 | + </div> |
| 41 | + <div className="text-md"> |
| 42 | + {msg.message} |
| 43 | + </div> |
| 44 | + </div> |
| 45 | + ))} |
| 46 | + </div> |
| 47 | + </div> |
| 48 | + |
| 49 | + <div className="p-2 flex gap-2"> |
| 50 | + <input |
| 51 | + type="text" |
| 52 | + value={message} |
| 53 | + onChange={(e) => setMessage(e.target.value)} |
| 54 | + className="w-full p-2 rounded-md text-black" |
| 55 | + placeholder="Type a message..." |
| 56 | + /> |
| 57 | + <button |
| 58 | + onClick={handleSendMessage} |
| 59 | + className="bg-blue-700 text-white p-2 rounded-md hover:bg-blue-600 focus:outline-none focus:bg-blue-600" |
| 60 | + > |
| 61 | + Send |
| 62 | + </button> |
| 63 | + </div> |
| 64 | + </div> |
| 65 | + ); |
| 66 | +}; |
| 67 | + |
| 68 | +export default UserChat; |
0 commit comments