React Components

Chat Box Component

Ask questions and get answers

ChatBox Component

The ChatBox component provides an AI-powered chat interface for your documents. Users can ask questions and get answers with optional streaming for a better user experience.

Installation

bash
npm install @easyrag/react-components

Basic Usage

tsx
import { ChatBox } from '@easyrag/react-components'; function App() { return ( <ChatBox token={yourToken} datasetId="my-dataset" /> ); }

Features

  • AI-Powered Answers - Get answers from your documents
  • Streaming Responses - Real-time response generation
  • Message History - Full conversation context
  • Auto-Scroll - Smooth scroll to latest messages
  • Initial Messages - Pre-populate conversations
  • Filtering - Query specific document subsets
  • Theming - 3 built-in themes + custom styling

Props

Required Props

PropTypeDescription
tokenstringAuthentication token (frontend token recommended)
datasetIdstringDataset ID to query

Optional Props

PropTypeDefaultDescription
apiUrlstringhttps://api.easyrag.com/v1API base URL
filtersarray[]Metadata filters to apply
streambooleantrueEnable streaming responses
maxHeightstring'400px'Maximum chat height
initialMessagesarray[]Pre-populate with messages
theme'default' | 'minimal' | 'custom''default'Visual theme
classNamestring''Additional CSS classes
customStylesobject{}Custom CSS class overrides
labelsobject{}Custom text labels
showTimestampbooleanfalseShow message timestamps
showPoweredBybooleantrueShow "Powered by EasyRAG"
poweredByUrlstringhttps://easyrag.comPowered by link URL

Callback Props

PropTypeDescription
onMessage(message: Message) => voidCalled when message is added
onError(error: Error) => voidCalled when an error occurs
onStreamStart() => voidCalled when streaming starts
onStreamEnd() => voidCalled when streaming ends

Examples

Basic Chat

tsx
<ChatBox token={token} datasetId="my-dataset" />

With Streaming

tsx
<ChatBox token={token} datasetId="my-dataset" stream={true} maxHeight="600px" />

Without Streaming

tsx
<ChatBox token={token} datasetId="my-dataset" stream={false} />

With Initial Messages

tsx
<ChatBox token={token} datasetId="support-kb" initialMessages={[ { id: 1, role: 'assistant', content: 'Hi! I can help you find information in our knowledge base. What would you like to know?' } ]} />

Filtered Chat

tsx
<ChatBox token={token} datasetId="company-docs" filters={[ { key: 'department', match: { value: 'engineering' } }, { key: 'confidential', match: { value: false } } ]} />

With Callbacks

tsx
<ChatBox token={token} datasetId="my-dataset" onMessage={(message) => { console.log('New message:', message); // Save to database saveMessage(message); }} onStreamStart={() => { console.log('Streaming started'); }} onStreamEnd={() => { console.log('Streaming ended'); }} onError={(error) => { console.error('Chat error:', error); toast.error('Failed to send message'); }} />

Custom Styling

tsx
<ChatBox token={token} datasetId="my-dataset" theme="custom" customStyles={{ container: 'my-chat-wrapper', messagesContainer: 'my-messages', messageUser: 'my-user-message', messageAssistant: 'my-assistant-message', input: 'my-input', button: 'my-button', }} />

Custom Labels

tsx
<ChatBox token={token} datasetId="my-dataset" labels={{ placeholder: 'Ask me anything...', buttonSend: 'Submit', buttonSending: 'Sending...', emptyState: 'Start a conversation!', }} />

Themes

Default Theme

Modern, polished design with EasyRAG branding:

tsx
<ChatBox token={token} datasetId="dataset" theme="default" />

Minimal Theme

Clean, simple styling:

tsx
<ChatBox token={token} datasetId="dataset" theme="minimal" />

Custom Theme

Full control over styling:

tsx
<ChatBox token={token} datasetId="dataset" theme="custom" customStyles={{ container: 'bg-white rounded-lg shadow-lg', messagesContainer: 'bg-gray-50 p-4 space-y-3', messageUser: 'bg-blue-600 text-white rounded-lg p-3', messageAssistant: 'bg-white border rounded-lg p-3', input: 'border-2 border-gray-300 rounded-lg p-3', button: 'bg-blue-600 text-white px-6 py-3 rounded-lg', }} />

TypeScript

Full TypeScript support included:

typescript
import type { ChatBoxProps, Message } from '@easyrag/react-components'; interface Message { id: number | string; role: 'user' | 'assistant'; content: string; } const props: ChatBoxProps = { token: 'your-token', datasetId: 'my-dataset', stream: true, onMessage: (message: Message) => { console.log(message); } };

Styling

Target specific elements with CSS:

css
/* Container */ .easyrag-chat-box { } /* Messages container */ .easyrag-chat-box .messages { } /* User message */ .easyrag-chat-box .message-user { } /* Assistant message */ .easyrag-chat-box .message-assistant { } /* Input form */ .easyrag-chat-box form { } /* Input field */ .easyrag-chat-box input { } /* Send button */ .easyrag-chat-box button { }

Streaming vs Non-Streaming

Streaming (Recommended)

Shows answers as they're generated:

tsx
<ChatBox token={token} datasetId="dataset" stream={true} onStreamStart={() => { console.log('Generating answer...'); }} onStreamEnd={() => { console.log('Answer complete'); }} />

Pros:

  • Better UX (see progress)
  • Feels faster
  • User can read while generating

Cons:

  • Slightly more complex
  • Can't edit until complete

Non-Streaming

Waits for complete answer:

tsx
<ChatBox token={token} datasetId="dataset" stream={false} />

Pros:

  • Simpler implementation
  • Complete answer arrives at once

Cons:

  • Appears slower
  • User waits with no feedback

Multi-Tenant Usage

Chat with user-specific data:

tsx
<ChatBox token={token} datasetId="shared-dataset" filters={[ { key: 'userId', match: { value: currentUser.id } }, { key: 'teamId', match: { value: currentUser.teamId } } ]} />

Integration with Other Components

With FileUpload

tsx
function DocumentChat() { const [hasFiles, setHasFiles] = useState(false); return ( <> <FileUpload token={token} datasetId="dataset" onUploadComplete={() => setHasFiles(true)} /> {hasFiles && ( <ChatBox token={token} datasetId="dataset" initialMessages={[ { id: 1, role: 'assistant', content: 'Files uploaded! What would you like to know?' } ]} /> )} </> ); }

With SearchBox

tsx
function SearchAndChat() { const [searchResults, setSearchResults] = useState([]); return ( <> <SearchBox token={token} datasetId="dataset" onResults={(results) => setSearchResults(results)} /> {searchResults.length > 0 && ( <ChatBox token={token} datasetId="dataset" initialMessages={[ { id: 1, role: 'assistant', content: `I found ${searchResults.length} relevant documents. What would you like to know about them?` } ]} /> )} </> ); }

Use Cases

Customer Support

tsx
<ChatBox token={token} datasetId="support-kb" initialMessages={[ { id: 1, role: 'assistant', content: 'Hi! I can help with account, billing, and technical questions. How can I assist you?' } ]} filters={[ { key: 'category', match: { value: 'public' } } ]} />

Internal Documentation

tsx
<ChatBox token={token} datasetId="company-docs" filters={[ { key: 'department', match: { value: user.department } }, { key: 'accessLevel', match: { value: user.accessLevel } } ]} initialMessages={[ { id: 1, role: 'assistant', content: `Welcome ${user.name}! Ask me about ${user.department} documentation.` } ]} />

Research Assistant

tsx
<ChatBox token={token} datasetId="research-papers" stream={true} maxHeight="700px" initialMessages={[ { id: 1, role: 'assistant', content: 'I can help you explore research papers. Ask me anything!' } ]} />

Best Practices

1. Use Frontend Tokens

Generate short-lived tokens from your backend:

typescript
// Backend app.post('/api/tokens/create', authenticate, async (req, res) => { const token = signFrontendToken({ customerId: req.user.id, datasetId: req.body.datasetId, ttlSeconds: 3600 }); res.json({ token }); }); // Frontend const token = await fetch('/api/tokens/create') .then(r => r.json()) .then(d => d.token);

2. Save Conversation History

tsx
<ChatBox token={token} datasetId="dataset" onMessage={(message) => { // Save to your database saveMessage({ userId: currentUser.id, datasetId: 'dataset', role: message.role, content: message.content, timestamp: new Date() }); }} />

3. Track Usage

tsx
<ChatBox token={token} datasetId="dataset" onMessage={(message) => { if (message.role === 'user') { analytics.track('chat_message_sent', { datasetId: 'dataset', messageLength: message.content.length }); } }} />

4. Handle Errors

tsx
<ChatBox token={token} datasetId="dataset" onError={(error) => { console.error('Chat error:', error); toast.error('Failed to send message. Please try again.'); // Report to error tracking Sentry.captureException(error); }} />

5. Set Appropriate Filters

tsx
<ChatBox token={token} datasetId="dataset" filters={[ // Security { key: 'userId', match: { value: currentUser.id } }, // Relevance { key: 'language', match: { value: 'en' } }, { key: 'status', match: { value: 'published' } } ]} />

Accessibility

The ChatBox component includes:

  • Semantic HTML
  • Keyboard navigation
  • ARIA labels
  • Focus management
  • Screen reader support
  • Auto-scroll to latest message

Browser Support

  • Chrome/Edge: Latest 2 versions
  • Firefox: Latest 2 versions
  • Safari: Latest 2 versions

Related Components

Support

Need help? Contact us at: