File size: 1,712 Bytes
a425c2c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import React, { useState } from 'react';
import axios from 'axios';
const Chatbot = () => {
const [input, setInput] = useState('');
const [conversation, setConversation] = useState([]);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInput(e.target.value);
};
const handleSendMessage = () => {
const newMessage = { text: input, sender: 'user' };
setConversation((prevConversation) => [...prevConversation, newMessage]);
axios.post('https://example.com/api/chatbot', { input })
.then((response) => {
const botResponse = { text: response.data, sender: 'bot' };
setConversation((prevConversation) => [...prevConversation, botResponse]);
})
.catch((error) => {
console.error(error);
});
setInput('');
};
return (
<div className="max-w-md mx-auto p-4 bg-gray-100 rounded-md shadow-md">
<h1 className="text-lg font-bold mb-4">Chatbot</h1>
<ul className="mb-4">
{conversation.map((message, index) => (
<li key={index} className={`text-lg ${message.sender === 'user' ? 'text-blue-600' : 'text-green-600'}`}>
{message.text}
</li>
))}
</ul>
<input
type="text"
value={input}
onChange={handleInputChange}
className="w-full p-2 mb-4 border border-gray-400 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
/>
<button
onClick={handleSendMessage}
className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
>
Send
</button>
</div>
);
};
export default Chatbot;
|