react-file-previews
v0.9.0
Published
A dynamic, extensible React component library for previewing files from URLs.
Downloads
1,047
Readme
React File Previews
A dynamic, extensible React component library for previewing files from URLs.
Features
- MIME-type Detection: Uses
HEADrequests to determine the file type. - Extensible Registry: Easy to add support for new file types (Video, PDF, etc.).
- TypeScript First: Full type safety for props and registry handlers.
Supported File Types
The following file types are supported out of the box:
- Images: All
image/*types (e.g., PNG, JPEG, GIF, SVG, WebP, etc.) - Audio: All
audio/*types (e.g., MP3, WAV, OGG) - Video: All
video/*types (e.g., MP4, WebM) - PDF: PDF documents (
application/pdf) - CSV: CSV spreadsheets (
text/csv) - Markdown: Markdown documents (
text/markdown) with Preview and Code tabs - Text/Code: Plain text, JSON, JavaScript, and XML
- YAML: YAML files (
application/x-yaml,text/yaml) - Word Documents:
.docand.docxfiles - Excel Spreadsheets:
.xlsand.xlsxfiles - PowerPoint Presentations:
.pptand.pptxfiles
Installation
npm install react-file-previewsUsage
Basic Usage
import { FilePreview } from 'react-file-previews';
function App() {
return (
<div>
<FilePreview url="https://example.com/image.png" />
</div>
);
}Advanced Usage (Custom Loaders/Errors)
<FilePreview
url="https://example.com/file.jpg"
loadingComponent={<span>Fetching file info...</span>}
errorComponent={(err) => <span>Failed: {err.message}</span>}
fallback={<span>Cannot preview this file type</span>}
/>How it Works
- The
FilePreviewcomponent uses theuseFileTypehook. useFileTypeperforms aHEADrequest to the URL.- The
Content-Typeheader is extracted. - The
previewRegistryis searched for a matching handler. - If found, the specific handler (e.g.,
ImagePreview) is rendered.
Extending the Library
To add support for a new file type (e.g., Video), you can add a new entry to the previewRegistry:
- Create your component:
const VideoPreview = ({ url }) => <video src={url} controls />;- Add it to the registry (in your local code if you want to extend it):
import { previewRegistry } from 'react-file-previews';
previewRegistry.push({
test: (mimeType) => mimeType.startsWith('video/'),
component: VideoPreview,
});