React Components

Search Box Component

Search documents

SearchBox Component

The SearchBox component provides a ready-to-use semantic search interface for your documents. Users can search their indexed content and view results with relevance scores.

Installation

bash
npm install @easyrag/react-components

Basic Usage

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

Features

  • Semantic Search - Natural language queries
  • Instant Results - Fast vector search
  • Relevance Scores - See how well results match
  • Metadata Display - View document metadata
  • Custom Rendering - Render results your way
  • Filtering - Search within specific metadata
  • Theming - 3 built-in themes + custom styling

Props

Required Props

PropTypeDescription
tokenstringAuthentication token (frontend token recommended)
datasetIdstringDataset ID to search within

Optional Props

PropTypeDefaultDescription
apiUrlstringhttps://api.easyrag.com/v1API base URL
filtersarray[]Metadata filters to apply
limitnumber5Number of results to fetch
maxResultsnumber10Maximum results to display
showScorebooleantrueDisplay relevance scores
showMetadatabooleanfalseDisplay document metadata
theme'default' | 'minimal' | 'custom''default'Visual theme
classNamestring''Additional CSS classes
customStylesobject{}Custom CSS class overrides
labelsobject{}Custom text labels
showPoweredBybooleantrueShow "Powered by EasyRAG"
poweredByUrlstringhttps://easyrag.comPowered by link URL

Callback Props

PropTypeDescription
onSearch(query: string) => voidCalled when search is submitted
onResults(results: SearchResult[]) => voidCalled when results are received
onError(error: Error) => voidCalled when an error occurs
renderResult(result: SearchResult, index: number) => ReactNodeCustom result renderer

Examples

Basic Search

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

With Relevance Scores

tsx
<SearchBox token={token} datasetId="my-dataset" showScore={true} showMetadata={false} />

Filtered Search

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

With Callbacks

tsx
<SearchBox token={token} datasetId="my-dataset" onSearch={(query) => { console.log('Searching for:', query); }} onResults={(results) => { console.log(`Found ${results.length} results`); // Track in analytics analytics.track('search', { query, resultsCount: results.length }); }} onError={(error) => { console.error('Search failed:', error); }} />

Custom Result Rendering

tsx
<SearchBox token={token} datasetId="my-dataset" renderResult={(result, index) => ( <div className="custom-result"> <h3>{result.metadata.title || 'Untitled'}</h3> <p>{result.pageContent}</p> <div className="metadata"> <span>Source: {result.metadata.source}</span> <span>Score: {(result.score * 100).toFixed(1)}%</span> </div> </div> )} />

Custom Styling

tsx
<SearchBox token={token} datasetId="my-dataset" theme="custom" customStyles={{ container: 'my-search-wrapper', input: 'my-search-input', button: 'my-search-button', resultCard: 'my-result-card', }} />

Custom Labels

tsx
<SearchBox token={token} datasetId="my-dataset" labels={{ placeholder: 'Search documentation...', buttonSearch: 'Find', buttonSearching: 'Searching...', emptyState: 'No results found. Try different keywords.', }} />

Themes

Default Theme

Modern, polished design with EasyRAG branding:

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

Minimal Theme

Clean, simple styling:

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

Custom Theme

Full control over styling:

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

TypeScript

Full TypeScript support included:

typescript
import type { SearchBoxProps, SearchResult } from '@easyrag/react-components'; interface SearchResult { score: number; pageContent: string; metadata: Record<string, any>; } const props: SearchBoxProps = { token: 'your-token', datasetId: 'my-dataset', showScore: true, onResults: (results: SearchResult[]) => { console.log(results); } };

Styling

Target specific elements with CSS:

css
/* Container */ .easyrag-search-box { } /* Form */ .easyrag-search-box form { } /* Input */ .easyrag-search-box input { } /* Button */ .easyrag-search-box button { } /* Results container */ .easyrag-search-box .results { } /* Individual result */ .easyrag-search-box .result { }

Multi-Tenant Usage

Search within user-specific data:

tsx
<SearchBox 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 DocumentSearch() { const [hasFiles, setHasFiles] = useState(false); return ( <> <FileUpload token={token} datasetId="dataset" onUploadComplete={() => setHasFiles(true)} /> {hasFiles && ( <SearchBox token={token} datasetId="dataset" /> )} </> ); }

With ChatBox

tsx
function SmartSearch() { const [searchQuery, setSearchQuery] = useState(''); return ( <> <SearchBox token={token} datasetId="dataset" onSearch={(query) => setSearchQuery(query)} /> {searchQuery && ( <ChatBox token={token} datasetId="dataset" initialMessages={[ { id: 1, role: 'user', content: `Tell me more about: ${searchQuery}` } ]} /> )} </> ); }

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. Filter Appropriately

Apply filters for security and relevance:

tsx
<SearchBox token={token} datasetId="dataset" filters={[ // Security: only user's data { key: 'userId', match: { value: currentUser.id } }, // Relevance: only published docs { key: 'status', match: { value: 'published' } } ]} />

3. Track Analytics

Monitor search behavior:

tsx
<SearchBox token={token} datasetId="dataset" onSearch={(query) => { analytics.track('search_started', { query }); }} onResults={(results) => { analytics.track('search_completed', { query, resultsCount: results.length, hasResults: results.length > 0 }); }} />

4. Handle Errors Gracefully

tsx
<SearchBox token={token} datasetId="dataset" onError={(error) => { console.error('Search error:', error); toast.error('Search failed. Please try again.'); }} />

Accessibility

The SearchBox component includes:

  • Semantic HTML
  • Keyboard navigation
  • ARIA labels
  • Focus management
  • Screen reader support

Browser Support

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

Related Components

Support

Need help? Contact us at: