doc-preview.tsx
Overview
doc-preview.tsx defines a React functional component DocPreviewer that fetches, parses, and renders the content of a Microsoft Word document (.docx) from a given URL as HTML. It uses the mammoth library to convert the .docx binary data into clean HTML, applies some default styling to paragraphs and headings, and displays a loading spinner while the document is being fetched and processed.
This component is designed to provide a lightweight and user-friendly document preview experience within a React application, abstracting away the complexities of document parsing and rendering.
Component: DocPreviewer
Description
DocPreviewer is a React functional component that accepts a document URL and optional class names. It asynchronously fetches the document as a blob, converts it to HTML using the mammoth library, and renders the resulting styled HTML content inside a styled container. During loading, a spinner is displayed.
Props
Prop | Type | Required | Description |
|---|---|---|---|
|
| Yes | The URL of the document (.docx) to preview. |
|
| No | Optional additional CSS class for styling. |
State
htmlContent: string– Stores the converted HTML content of the document.loading: boolean– Tracks whether the document is currently being fetched and parsed.
Behavior and Workflow
When the component mounts or the
urlprop changes, it triggersfetchDocument().fetchDocument():Sets
loadingtotrue.Sends a GET request to the given
urlusing a customrequestutility, expecting a blob response.On error during fetching, it shows an error message and logs the error.
On successful fetch:
Converts the blob data to an
ArrayBuffer.Uses mammoth.convertToHtml to convert
.docxbinary data into HTML, including default style mappings.Enhances the resulting HTML by adding margin and font-weight CSS classes to paragraphs (
<p>) and headings (<h1>to<h6>).Updates
htmlContentstate with the styled HTML.
Catches and reports errors during parsing.
Sets
loadingtofalseafter processing.
The component renders:
A container
divwith base styling and optional custom class.A
Spinloading indicator overlay whenloadingistrue.The parsed HTML content injected using dangerouslySetInnerHTML when not loading.
Usage Example
import { DocPreviewer } from './doc-preview';
function MyDocumentPage() {
const documentUrl = 'https://example.com/files/sample.docx';
return (
<div style={{ width: '600px', height: '800px' }}>
<DocPreviewer url={documentUrl} className="my-custom-class" />
</div>
);
}
Implementation Details
Fetching:
Uses a custom request utility (
request) with{ responseType: 'blob' }to obtain raw binary data of the document.Includes an error callback to show user-friendly error messages.
Document Conversion:
Uses
mammothlibrary, which extracts semantic HTML from.docxfiles, focusing on clean markup without inline styles.Enables
includeDefaultStyleMapfor some baseline style mapping.
Post-processing HTML:
Adds margin-bottom spacing to paragraphs (
<p>) by replacing<p>with<p class="mb-2">.Adds font-weight and vertical margin classes to headings (
<h1>to<h6>).This provides consistent spacing and typography without inline styles.
Loading State:
Displays a centered spinner overlay (
Spincomponent) while the document is being fetched and converted.Uses absolute positioning and flexbox for centering.
Styling and Layout:
The container has padding, background, border, and rounded corners.
Accepts additional CSS classes via
classNameprop for customization.
Error Handling:
User-visible error messages via a UI message component.
Console logs for developers.
Interaction with Other Parts of the System
requestutility: Abstracts the HTTP request logic, likely wrappingfetchoraxios. Handles network communication to fetch the document.messageUI component: Used to display user-facing notifications for errors.SpinUI component: Displays a loading spinner overlay while fetching/parsing.mammothlibrary: External dependency for parsing.docxfiles into HTML.CSS Utilities:
Uses
classNameslibrary for conditional class concatenation.Utilizes Tailwind CSS utility classes (
mb-2,font-semibold,mt-4, etc.) for styling.
This component can be embedded anywhere in the React app where document previews are needed, requiring only a valid .docx URL.
Mermaid Component Diagram
componentDiagram
component DocPreviewer {
+props: { url: string; className?: string }
+state: htmlContent: string
+state: loading: boolean
+fetchDocument(): Promise<void>
+useEffect(() => fetchDocument(), [url])
+render()
}
component request
component message
component Spin
component mammoth
DocPreviewer --> request : fetch document blob
DocPreviewer --> mammoth : convertToHtml(blob)
DocPreviewer --> message : error notifications
DocPreviewer --> Spin : loading spinner display
Summary
The DocPreviewer component is a self-contained React component for fetching and rendering Word documents as styled HTML previews. It handles the asynchronous complexity of network fetching and document parsing while providing a clean and styled UI for users. Its dependency on mammoth ensures good semantic HTML output, making it suitable for displaying document content in web applications without heavy dependencies or complex server-side processing.