Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views2 pages

SRC Components Chat - TSX

This document is a React component for a chat interface that displays chat messages and allows users to send new messages. It utilizes hooks for state management and references for scrolling behavior. The component includes a form for inputting messages and dynamically updates the chat history as new messages are sent.

Uploaded by

sopnil260
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

SRC Components Chat - TSX

This document is a React component for a chat interface that displays chat messages and allows users to send new messages. It utilizes hooks for state management and references for scrolling behavior. The component includes a form for inputting messages and dynamically updates the chat history as new messages are sent.

Uploaded by

sopnil260
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import React, { useState, useRef, useEffect } from "react";

import { ChatMessage } from "../types";

interface Props {
chatHistory: ChatMessage[];
onSend: (msg: string) => void;
}
export default function Chat({ chatHistory, onSend }: Props) {
const [input, setInput] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const chatEndRef = useRef<HTMLDivElement>(null);

useEffect(() => {
chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [chatHistory]);

const handleSend = (e: React.FormEvent) => {


e.preventDefault();
if (input.trim()) {
onSend(input.trim());
setInput("");
inputRef.current?.focus();
}
};

return (
<div className="bg-white rounded shadow p-4 mt-2 flex flex-col h-96 overflow-
hidden">
<div className="flex-1 overflow-y-auto mb-2">
{chatHistory.map((msg, idx) => (
<div
key={idx}
className={`mb-2 flex ${
msg.sender === "user" ? "justify-end" : "justify-start"
}`}
>
<div
className={`px-3 py-2 rounded-lg max-w-xs ${
msg.sender === "user"
? "bg-blue-500 text-white"
: "bg-gray-100 text-gray-700"
}`}
>
{msg.text}
</div>
</div>
))}
<div ref={chatEndRef} />
</div>
<form onSubmit={handleSend} className="flex gap-2 items-center">
<input
ref={inputRef}
type="text"
className="flex-1 border rounded px-3 py-2 focus:outline-blue-300"
placeholder="Ask in Bangla or English..."
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button
type="submit"
className="bg-blue-600 text-white px-4 py-2 rounded font-semibold
hover:bg-blue-700 transition"
>
Send
</button>
</form>
</div>
);
}

You might also like