Chat Conversation Block
The Chat Conversation Component is a fully customizable and accessible chat interface built with React and TypeScript. It provides a complete conversation view with message display, input handling, and flexible customization options for real-time messaging applications.
π Installationβ
npm install @nodeblocks/frontend-chat-conversation-block@0.2.1
π Usageβ
import {ChatConversation} from '@nodeblocks/frontend-chat-conversation-block';
- Basic Usage
- Advanced Usage
function SimpleChatConversation() { const [messages, setMessages] = useState([ { title: 'John Doe', content: 'Hello! How are you doing today?', id: 'message-001', createdAt: '2025-02-01T10:00:00Z', isOwnMessage: false, avatar: { sx: {bgcolor: 'primary.main'}, }, }, { title: 'You', content: 'Hi! I am doing great, thanks for asking!', id: 'message-002', createdAt: '2025-02-01T10:01:00Z', isOwnMessage: true, }, ]); return ( <ChatConversation chatView={{ heading: { avatar: { sx: {bgcolor: 'secondary.main'}, }, buttonHref: '/home', }, isLoading: false, }} onInputChange={(text) => { console.log('Input changed:', text); }} onMessageSubmit={(text) => { console.log('Message submitted:', text); setMessages(prev => [ ...prev, { title: 'You', content: text, id: 'message-' + Date.now(), createdAt: new Date().toISOString(), isOwnMessage: true, }, ]); }} commentInput={{ isDisabled: false, }} commentSubmitButton={{ isDisabled: false, }} messages={messages} labels={{ chatViewHeadingButtonText: 'Home', chatViewHeadingText: 'Conversation', }} onNavigate={(url) => { console.log('Navigate to:', url); }} placeholders={{ commentInput: 'Type a message...', }} > <ChatConversation.Heading /> <ChatConversation.Body /> </ChatConversation> ); }
function AdvancedChatConversation() { const [messages, setMessages] = useState([ { title: 'Support Team', content: 'Welcome to our support chat! How can we help you today?', id: 'message-001', createdAt: '2025-02-01T10:00:00Z', isOwnMessage: false, avatar: { sx: {bgcolor: 'info.main'}, src: '/support-avatar.jpg', }, }, { title: 'You', content: 'I need help with my account settings.', id: 'message-002', createdAt: '2025-02-01T10:01:00Z', isOwnMessage: true, }, ]); return ( <ChatConversation chatView={{ isLoading: false, }} onInputChange={(text) => { console.log('Input changed:', text); }} onMessageSubmit={(text) => { console.log('Message submitted:', text); setMessages(prev => [ ...prev, { title: 'You', content: text, id: 'message-' + Date.now(), createdAt: new Date().toISOString(), isOwnMessage: true, }, ]); }} commentInput={{ isDisabled: false, errorText: '', }} commentSubmitButton={{ isDisabled: false, }} messages={messages} labels={{ chatViewHeadingButtonText: 'Dashboard', chatViewHeadingText: 'Support Chat', }} onNavigate={(url) => { console.log('Navigate to:', url); }} placeholders={{ commentInput: 'Ask a question...', }} className="custom-chat-container" sx={{maxHeight: '600px'}} > {({defaultBlocks}) => ({ blocks: { ...defaultBlocks, toolbar: ( <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', backgroundColor: '#e7f3ff', borderBottom: '1px solid #b3d9ff', fontSize: '14px', color: '#0066cc', }} > <span>π’ Online - Support Agent</span> <span>Response time: ~2 min</span> </div> ), statusBar: ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '8px', backgroundColor: '#f8f9fa', borderTop: '1px solid #dee2e6', fontSize: '12px', color: '#6c757d', }} > <span> π¬ {messages.length} messages β’ Last updated: {new Date().toLocaleTimeString()} </span> </div> ), }, blockOrder: ['heading', 'toolbar', 'body', 'statusBar'], })} </ChatConversation> ); }
π§ Props Referenceβ
Main Component Propsβ
| Prop | Type | Default | Description |
|---|---|---|---|
onMessageSubmit | (text: string) => void | undefined | Callback when submitting a message |
onInputChange | (text: string) => void | undefined | Callback on comment input change |
commentInput | CommentInputConfig | undefined | Configuration for the comment input at the bottom |
commentSubmitButton | {isDisabled?: boolean;} | undefined | Configuration for the comment submit button |
chatView | ChatViewConfig | Required | Chat panel configuration |
messages | Message[] | Required | Array of messages to display in the chat view |
labels | LabelsConfig | Required | Label text configuration |
onNavigate | (url: string) => void | Required | Navigation callback (required for href) |
placeholders | {commentInput: string} | Required | Placeholder text configuration |
className | string | undefined | Additional CSS class name for styling |
children | BlocksOverride | undefined | Custom block components to override default rendering |
sx | SxProps<Theme> | undefined | MUI system props for custom styling |
Note: This component inherits all MUI Stack component props (e.g., direction, spacing, divider, etc.).
Sub-Componentsβ
The ChatConversation component provides several sub-components. All sub-components receive their default values from the main component's context and can override these values through props.
ChatConversation.Headingβ
| Prop | Type | Default | Description |
|---|---|---|---|
labels | LabelsConfig | Context values | Label configuration (overrides context) |
chatView | ChatViewConfig | Context values | Chat view configuration (overrides context) |
onNavigate | (url: string) => void | Context values | Navigation callback (overrides context) |
className | string | undefined | Additional CSS class name for styling |
children | ReactNode | Default heading content | Custom content to override default heading |
direction | StackDirection | "row" | Flex direction for the heading layout |
spacing | number | string | 2 | Spacing between heading elements |
sx | SxProps<Theme> | undefined | MUI system props for custom styling |
Note: This component inherits all MUI Stack component props.
ChatConversation.Bodyβ
| Prop | Type | Default | Description |
|---|---|---|---|
onMessageSubmit | (text: string) => void | Context values | Message submit callback (overrides context) |
onInputChange | (text: string) => void | Context values | Input change callback (overrides context) |
commentInput | CommentInputConfig | Context values | Comment input configuration (overrides context) |
commentSubmitButton | {isDisabled?: boolean;} | Context values | Submit button configuration (overrides context) |
chatView | ChatViewConfig | Context values | Chat view configuration (overrides context) |
messages | Message[] | Context values | Messages array (overrides context) |
onNavigate | (url: string) => void | Context values | Navigation callback (overrides context) |
placeholders | {commentInput: string} | Context values | Placeholder configuration (overrides context) |
className | string | undefined | Additional CSS class name for styling |
sx | SxProps<Theme> | undefined | MUI system props for custom styling |
Note: This component accepts MUI Box component props for styling purposes.
π¨ Configuration examplesβ
The component uses MUI Avatar props for avatar customization. Here's how to configure avatars:
Message Avatarβ
const message = {
id: 'msg-001',
content: 'Hello!',
createdAt: new Date().toISOString(),
avatar: {
// MUI Avatar props
src: '/path/to/image.jpg', // Image source
srcSet: '/path/to/image@2x.jpg 2x', // Responsive images
sx: {bgcolor: 'primary.main'}, // Custom styling
children: 'JD', // Fallback content (initials)
// Extended props
href: '/users/john-doe', // Navigation link (requires onNavigate)
isLoading: false, // Show loading placeholder
// For link behavior
component: 'a', // Render as anchor tag
},
};
Heading Avatarβ
<ChatConversation
chatView={{
heading: {
avatar: {
src: '/team-avatar.jpg',
sx: {width: 32, height: 32},
isLoading: false,
// For clickable avatar
component: 'a',
href: '/team-profile',
},
buttonHref: '/home',
},
}}
// ...other props
/>
π§ TypeScript Supportβ
Full TypeScript support with comprehensive type definitions:
import {ChatConversation} from '@nodeblocks/frontend-chat-conversation-block';
import {AvatarProps} from '@mui/material';
import {useState} from 'react';
interface LabelsConfig {
chatViewHeadingButtonText?: string;
chatViewHeadingText?: string;
}
interface CommentInputConfig {
/** Disables input (while submitting or similar) */
isDisabled?: boolean;
/** Error message to show below the comment input field */
errorText?: string;
}
interface ChatViewConfig {
heading?: {
/** MUI Avatar props with optional isLoading state */
avatar?:
| (Partial<AvatarProps> & { isLoading?: boolean })
| (Partial<AvatarProps<'a'>> & { isLoading?: boolean; component: 'a' });
buttonHref: string;
};
/**
* Loading state for either overall view or for previous messages
* (depends on whether messages is empty)
*/
isLoading?: boolean;
/**
* Callback when the user has scrolled up and reached the top of the chat view.
* This can be used to fetch more messages from the server.
*/
onScrollTop?: (earliestMessageId: string) => void;
}
// Message interface
interface Message {
avatar?: {
sx?: Record<string, unknown>;
src?: string;
href?: string;
isLoading?: boolean;
};
content: string;
createdAt: string;
id: string;
isOwnMessage?: boolean;
title?: string;
}
// Complete typed example
function TypedChatConversation() {
const [messages, setMessages] = useState<Message[]>([
{
title: 'Support Agent',
content: 'Hello! How can I help you today?',
id: 'msg-001',
createdAt: '2025-02-01T09:00:00Z',
isOwnMessage: false,
avatar: {
sx: {bgcolor: 'info.main'},
src: '/path/to/agent-avatar.jpg',
},
},
]);
const [inputValue, setInputValue] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [inputError, setInputError] = useState<string | undefined>();
const handleInputChange = (text: string) => {
setInputValue(text);
if (text.length > 500) {
setInputError('Message too long (max 500 characters)');
} else {
setInputError(undefined);
}
};
const handleMessageSubmit = async (text: string) => {
if (!text.trim()) return;
setIsSubmitting(true);
const userMessage: Message = {
title: 'You',
content: text,
id: `msg-${Date.now()}`,
createdAt: new Date().toISOString(),
isOwnMessage: true,
};
setMessages(prev => [...prev, userMessage]);
setInputValue('');
try {
await new Promise(resolve => setTimeout(resolve, 2000));
const responseMessage: Message = {
title: 'Support Agent',
content: 'Thank you for your message. Let me help you with that.',
id: `msg-${Date.now()}-response`,
createdAt: new Date().toISOString(),
isOwnMessage: false,
avatar: {
sx: {bgcolor: 'info.main'},
},
};
setMessages(prev => [...prev, responseMessage]);
} catch (error) {
console.error('Failed to send message:', error);
} finally {
setIsSubmitting(false);
}
};
const handleScrollTop = (earliestMessageId: string) => {
console.log('Loading more messages before:', earliestMessageId);
};
return (
<ChatConversation
chatView={{
heading: {
avatar: {
sx: {bgcolor: 'secondary.main', width: 32, height: 32},
src: '/path/to/avatar.jpg',
},
buttonHref: '/support/dashboard',
},
isLoading: isSubmitting,
onScrollTop: handleScrollTop,
}}
onInputChange={handleInputChange}
onMessageSubmit={handleMessageSubmit}
commentInput={{
isDisabled: isSubmitting,
errorText: inputError,
}}
commentSubmitButton={{
isDisabled: isSubmitting || Boolean(inputError) || !inputValue.trim(),
}}
messages={messages}
labels={{
chatViewHeadingButtonText: 'Back to Dashboard',
chatViewHeadingText: 'Customer Support',
}}
onNavigate={(url) => {
window.location.href = url;
}}
placeholders={{
commentInput: 'Type your message here...',
}}
className="custom-chat-container"
sx={{maxHeight: '600px'}}
>
<ChatConversation.Heading className="custom-chat-header" />
<ChatConversation.Body className="custom-chat-body" />
</ChatConversation>
);
}
π Notesβ
- Messages are grouped by date using the Luxon library with Japanese date format (
yyyyεΉ΄MMζddζ₯) - When a new message is added, the chat view automatically scrolls to the bottom
- The
onScrollTopcallback is triggered when the user scrolls to the top, useful for pagination - Pressing Enter (without Shift) submits the message; Shift+Enter creates a new line
- The component uses MUI's theming system for consistent styling
Built with β€οΈ using React, TypeScript, MUI, and Luxon.