Created
February 19, 2025 03:38
-
-
Save nandiraju/a7b9fbee3b86e7f0502532cba80a1280 to your computer and use it in GitHub Desktop.
Simple Chat UI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use client'; | |
| import { useState, useEffect, useRef } from "react"; | |
| export default function SimpleChat() { | |
| const [messages, setMessages] = useState([ | |
| { text: "Hello! How can I help you?", sender: "bot" } | |
| ]); | |
| const [input, setInput] = useState(""); | |
| const chatRef = useRef(null); | |
| useEffect(() => { | |
| chatRef.current?.scrollTo({ top: chatRef.current.scrollHeight, behavior: "smooth" }); | |
| }, [messages]); | |
| const sendMessage = () => { | |
| if (!input.trim()) return; | |
| setMessages([...messages, { text: input, sender: "user" }]); | |
| setInput(""); | |
| setTimeout(() => { | |
| setMessages(prev => [...prev, { text: "I'm just a demo bot!", sender: "bot" }]); | |
| }, 1000); | |
| }; | |
| return ( | |
| <div className="flex flex-col bg-gray-100 w-full h-full"> | |
| <div ref={chatRef} className="flex-1 space-y-2 p-4 overflow-y-auto"> | |
| {messages.map((msg, index) => ( | |
| <div key={index} className={`flex items-end ${msg.sender === "user" ? "justify-end" : "justify-start"}`}> | |
| {msg.sender === "bot" && <div className="bg-gray-400 mr-2 rounded-full w-8 h-8"></div>} | |
| <div className={`relative p-2 rounded-lg max-w-[75%] ${msg.sender === "user" ? "bg-blue-500 text-white self-end" : "bg-gray-200 text-gray-900"}`}> | |
| <span>{msg.text}</span> | |
| <div className={`absolute bottom-0 h-0 w-0 border-solid ${msg.sender === "user" ? "right-[-5px] border-t-[10px] border-l-[10px] border-t-transparent border-l-blue-500" : "left-[-5px] border-t-[10px] border-r-[10px] border-t-transparent border-r-gray-200"}`}></div> | |
| </div> | |
| {msg.sender === "user" && <div className="bg-blue-500 ml-2 rounded-full w-8 h-8"></div>} | |
| </div> | |
| ))} | |
| </div> | |
| <div className="flex bg-white shadow-md p-4"> | |
| <input | |
| type="text" | |
| className="flex-1 p-2 border rounded-l-lg focus:outline-none" | |
| value={input} | |
| onChange={(e) => setInput(e.target.value)} | |
| onKeyDown={(e) => e.key === "Enter" && sendMessage()} | |
| placeholder="Type a message..." | |
| /> | |
| <button className="bg-blue-500 p-2 rounded-r-lg text-white" onClick={sendMessage}> | |
| Send | |
| </button> | |
| </div> | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment