Message
The Message
component displays a chat interface message from either a user or an AI. It includes an avatar, a name, and a message content.
Hello, how are you?
Installation
npx ai-elements@latest add message
Usage
import { Message, MessageContent } from '@/components/ai-elements/message';
<Message from="user"> <MessageContent>Hi there!</MessageContent></Message>
Usage with AI SDK
Render messages in a list with useChat
.
Add the following component to your frontend:
app/page.tsx
'use client';
import { Message, MessageContent } from '@/components/ai-elements/message';import { useChat } from '@ai-sdk/react';import { Response } from '@/components/ai-elements/response';
const MessageDemo = () => { const { messages } = useChat();
return ( <div className="max-w-4xl mx-auto p-6 relative size-full rounded-lg border h-[600px]"> <div className="flex flex-col h-full"> {messages.map((message) => ( <Message from={message.role} key={message.id}> <MessageContent> {message.parts.map((part, i) => { switch (part.type) { case 'text': // we don't use any reasoning or tool calls in this example return ( <Response key={`${message.id}-${i}`}> {part.text} </Response> ); default: return null; } })} </MessageContent> </Message> ))} </div> </div> );};
export default MessageDemo;
Features
- Displays messages from both the user and AI assistant with distinct styling.
- Includes avatar images for message senders with fallback initials.
- Shows the sender's name through avatar fallbacks.
- Automatically aligns user and assistant messages on opposite sides.
- Uses different background colors for user and assistant messages.
- Accepts any React node as message content.
Notes
Always render the AIMessageContent
first, then the AIMessageAvatar
. The AIMessage
component is a wrapper that determines the alignment of the message.
Examples
Render Markdown
We can use the Response
component to render markdown content.
What is the weather in Tokyo?
Props
<Message />
from:
UIMessage["role"]
The role of the message sender ("user", "assistant", or "system").
[...props]?:
React.HTMLAttributes<HTMLDivElement>
Any other props are spread to the root div.
<MessageContent />
[...props]?:
React.HTMLAttributes<HTMLDivElement>
Any other props are spread to the content div.
<MessageAvatar />
src:
string
The URL of the avatar image.
name?:
string
The name to use for the avatar fallback (first 2 letters shown if image is missing).
[...props]?:
React.ComponentProps<typeof Avatar>
Any other props are spread to the underlying Avatar component.