React Components

File Upload Component

Upload and index files

The FileUpload component provides a drag-and-drop interface for uploading files to your EasyRAG dataset. It handles file selection, validation, progress tracking, and metadata attachment.

Installation

bash
npm install @easyrag/react-components

Basic Usage

tsx
import { FileUpload } from '@easyrag/react-components'; function App() { return ( <FileUpload token={yourToken} datasetId="my-dataset" onUploadComplete={(result) => { console.log('Uploaded files:', result.files); }} /> ); }

Props

Required Props

PropTypeDescription
tokenstringAuthentication token (API key or frontend token)
datasetIdstringDataset ID where files will be uploaded

Optional Props

PropTypeDefaultDescription
apiUrlstringhttps://api.easyrag.com/v1API base URL
maxFilesnumber10Maximum number of files per upload
maxFileSizenumberundefinedMaximum file size in bytes
acceptobjectundefinedAccepted file types (react-dropzone format)
metadataBuilderfunctionundefinedFunction to build metadata per file
chunkSizenumberundefinedTokens per chunk (override default)
chunkOverlapnumberundefinedOverlap between chunks

Callback Props

PropTypeDescription
onUploadStart(files: File[]) => voidCalled when upload begins
onUploadComplete(result: any) => voidCalled when upload succeeds
onUploadError(error: Error) => voidCalled when upload fails

Styling Props

PropTypeDefaultDescription
classNamestring''Additional CSS classes
theme'default' | 'minimal' | 'custom''default'Visual theme
customStylesobject{}Custom CSS classes per element
labelsobject{}Custom text labels

Branding Props

PropTypeDefaultDescription
showPoweredBybooleantrueShow "Powered by EasyRAG"
poweredByUrlstring'https://easyrag.com'URL for powered-by link

Examples

Basic File Upload

tsx
<FileUpload token={token} datasetId="my-dataset" onUploadComplete={(result) => { console.log(`Uploaded ${result.files.length} files`); }} />

Restrict File Types

tsx
<FileUpload token={token} datasetId="documents" accept={{ 'application/pdf': ['.pdf'], 'application/msword': ['.doc', '.docx'] }} maxFileSize={10 * 1024 * 1024} // 10MB />

Add Metadata to Files

tsx
<FileUpload token={token} datasetId="user-uploads" metadataBuilder={(file, index) => ({ userId: currentUser.id, department: currentUser.department, originalFileName: file.name, uploadedAt: new Date().toISOString(), uploadIndex: index })} />

Custom Chunking

tsx
<FileUpload token={token} datasetId="technical-docs" chunkSize={800} chunkOverlap={100} onUploadComplete={(result) => { console.log('Files indexed with custom chunking'); }} />

Multi-Tenant Upload

tsx
<FileUpload token={token} datasetId="shared-dataset" metadataBuilder={(file) => ({ customerId: currentCustomer.id, userId: currentUser.id, confidential: file.name.includes('confidential') })} />

Custom Styling

tsx
<FileUpload token={token} datasetId="my-dataset" theme="custom" customStyles={{ container: 'my-upload-container', dropzone: 'border-2 border-dashed border-blue-500 p-8', button: 'bg-blue-600 text-white px-6 py-2', error: 'text-red-600 font-semibold' }} />

Custom Labels

tsx
<FileUpload token={token} datasetId="my-dataset" labels={{ dropzone: 'Drop your documents here', dropzoneActive: 'Release to upload', uploading: 'Processing your files...', selectFiles: 'Choose Files' }} />

Minimal Theme

tsx
<FileUpload token={token} datasetId="my-dataset" theme="minimal" showPoweredBy={false} />

Metadata Builder

The metadataBuilder function is called for each file and returns metadata that will be attached to all chunks from that file.

tsx
metadataBuilder={(file: File, index: number) => { return { // Custom fields - use any keys you want userId: 'user_123', department: 'engineering', uploadDate: new Date().toISOString(), // File info originalName: file.name, fileSize: file.size, fileType: file.type, // Index in upload batch uploadIndex: index }; }}

Later, you can filter searches by these metadata fields:

tsx
<SearchBox token={token} datasetId="my-dataset" filters={[ { key: 'department', match: { value: 'engineering' } }, { key: 'userId', match: { value: 'user_123' } } ]} />

File Type Restrictions

Use the accept prop to restrict file types (uses react-dropzone format):

tsx
// Only PDFs accept={{ 'application/pdf': ['.pdf'] }} // PDFs and Word docs accept={{ 'application/pdf': ['.pdf'], 'application/msword': ['.doc'], 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'] }} // Images only accept={{ 'image/jpeg': ['.jpg', '.jpeg'], 'image/png': ['.png'] }} // Any file (default) accept={undefined}

Supported File Types

EasyRAG automatically processes these file types:

Documents

  • PDF (.pdf)
  • Microsoft Word (.doc, .docx)
  • Microsoft Excel (.xls, .xlsx)
  • Microsoft PowerPoint (.ppt, .pptx)
  • Plain text (.txt)
  • Markdown (.md)
  • CSV (.csv)

Media (with transcription)

  • Audio: MP3, WAV, M4A
  • Video: MP4, MOV, AVI

Error Handling

tsx
<FileUpload token={token} datasetId="my-dataset" onUploadError={(error) => { console.error('Upload failed:', error.message); // Show user-friendly message if (error.message.includes('INSUFFICIENT_CREDITS')) { alert('Out of credits. Please upgrade your plan.'); } else if (error.message.includes('FILE_TOO_LARGE')) { alert('File is too large. Maximum size is 10MB.'); } else { alert('Upload failed. Please try again.'); } }} />

Progress Tracking

tsx
<FileUpload token={token} datasetId="my-dataset" onUploadStart={(files) => { console.log(`Starting upload of ${files.length} files`); setIsUploading(true); }} onUploadComplete={(result) => { console.log('Upload complete!'); setIsUploading(false); refreshFileList(); }} onUploadError={(error) => { console.error('Upload failed'); setIsUploading(false); }} />

TypeScript

Full TypeScript support:

typescript
import type { FileUploadProps } from '@easyrag/react-components'; const uploadProps: FileUploadProps = { token: myToken, datasetId: 'my-dataset', maxFiles: 5, metadataBuilder: (file, index) => ({ userId: 'user_123', uploadIndex: index }) }; <FileUpload {...uploadProps} />

Custom Styles Reference

Available customStyles keys:

typescript
{ container?: string; // Outer wrapper dropzone?: string; // Drop zone area dropzoneActive?: string; // Drop zone when dragging fileList?: string; // File list container button?: string; // Buttons error?: string; // Error messages }

Best Practices

1. Use Frontend Tokens

tsx
// ✅ Good - token from backend const token = await fetch('/api/tokens/create').then(r => r.json()); <FileUpload token={token.token} datasetId="dataset" /> // ❌ Bad - API key in frontend <FileUpload token={process.env.REACT_APP_API_KEY} datasetId="dataset" />

2. Add Useful Metadata

tsx
// ✅ Good - searchable metadata metadataBuilder: (file) => ({ userId: currentUser.id, department: currentUser.department, documentType: getDocumentType(file.name), uploadDate: new Date().toISOString() }) // ❌ Bad - no metadata (harder to filter later) metadataBuilder: undefined

3. Set Appropriate Limits

tsx
// ✅ Good - reasonable limits <FileUpload maxFiles={10} maxFileSize={10 * 1024 * 1024} /> // ❌ Bad - no limits (potential abuse) <FileUpload />

4. Handle Errors Gracefully

tsx
// ✅ Good - user-friendly error handling <FileUpload onUploadError={(error) => { showNotification({ type: 'error', message: getUserFriendlyMessage(error) }); }} />

FAQ

Q: Can I upload multiple files at once?
A: Yes, use the maxFiles prop to control how many files can be uploaded in a single batch.

Q: How do I show upload progress?
A: Use the onUploadStart and onUploadComplete callbacks to track upload state.

Q: Can I customize the styling completely?
A: Yes, use theme="custom" and provide customStyles with your own CSS classes.

Q: What happens if upload fails?
A: The onUploadError callback is called with the error. The component displays an error message.

Q: Can I use this with Next.js?
A: Yes, the component works with Next.js. Make sure to use it in a client component ("use client").

Q: How do I hide the "Powered by" link?
A: Set showPoweredBy={false}.

Related