Components
Loading preview...
Here is Conversation component
npx shadcn@latest add https://21st.dev/r/vercel/conversation'use client';
import React, { useState, useEffect } from 'react';
import {
Conversation,
ConversationContent,
ConversationScrollButton,
} from '@/components/ui/conversation';
import { cn } from '@/lib/utils';
// Message component
type MessageProps = {
from: 'user' | 'bot';
children: React.ReactNode;
};
const Message = ({ from, children }: MessageProps) => (
<div
className={cn(
'my-2 flex',
from === 'user' ? 'justify-end' : 'justify-start'
)}
>
<div
className={cn(
'max-w-xs rounded-lg p-2',
from === 'user'
? 'bg-blue-500 text-white'
: 'bg-gray-200 text-gray-800'
)}
>
{children}
</div>
</div>
);
const MessageContent = ({ children }: { children: React.ReactNode }) => (
<div>{children}</div>
);
// Main chat component
export default function AutoChatExample() {
const [messages, setMessages] = useState<
{ from: 'user' | 'bot'; text: string }[]
>([]);
// Predefined conversation flow
const conversationFlow = [
{ from: 'user', text: 'Hi there!' },
{ from: 'bot', text: 'Hello! How are you doing?' },
{ from: 'user', text: 'I am doing great, thanks!' },
{ from: 'bot', text: 'Glad to hear that! What are you up to today?' },
{ from: 'user', text: 'Just working on some React projects.' },
{ from: 'bot', text: 'Awesome! React is fun to work with.' },
];
useEffect(() => {
if (messages.length < conversationFlow.length) {
const timer = setTimeout(() => {
setMessages((prev) => [
...prev,
conversationFlow[prev.length],
]);
}, 1200); // delay between messages
return () => clearTimeout(timer);
}
}, [messages]);
return (
<div className="w-full max-w-md mx-auto mt-10 border rounded-lg overflow-hidden shadow-md">
<Conversation className="relative w-full" style={{ height: '400px' }}>
<ConversationContent>
{messages.map((msg, idx) => (
<Message key={idx} from={msg.from}>
<MessageContent>{msg.text}</MessageContent>
</Message>
))}
</ConversationContent>
<ConversationScrollButton />
</Conversation>
</div>
);
}