The Document component is the primary entry point for rendering PDF files in react-pdf. It handles loading the file, managing the PDF.js lifecycle, and providing context to child components.
Key Usage Patterns
1. Basic Rendering
Pass a file prop (URL, file object, or parameter object) and use the render prop pattern to access the pdf object for rendering pages.
<Document
file="https://example.com/sample.pdf"
onLoadSuccess={({ pdf }) => console.log(`Loaded ${pdf.numPages} pages`)}
>
{({ pdf }) => (
<div>
{/* Render pages here using the pdf object */}
</div>
)}
</Document>
2. Handling Loading, Error, and No Data States
You can customize the UI for different lifecycle states using loading, error, and noData props.
<Document
file={myFile}
loading={<p>Please wait...</p>}
error={<p>Failed to load PDF.</p>}
noData={<p>No file selected.</p>}
/>
3. Managing Password Protected PDFs
Use the onPassword callback to handle password prompts.
<Document
file={protectedFile}
onPassword={(callback, reason) => {
const password = prompt('Enter password:');
callback(password);
}}
/>
Important Performance Note
Because Document uses strict equality (===) to detect changes in the file and options props, you must memoize these values (e.g., using useMemo or component state) to prevent unnecessary reloads and performance warnings.
// DO THIS
const file = useMemo(() => ({ url: '...' }), []);
const options = useMemo(() => ({ cMapUrl: '...' }), []);
<Document file={file} options={options} />