Appearance
Opening and displaying a document - React
You must call the open
method on the PdfDocument
component to load a document.
Use the useRef hook to obtain a reference to the element:
tsx
const pdfDocument = useRef<HTMLPdfDocumentELement>(null);
return (
<>
<PdfDocument ref={pdfDocument} />
</>
);
You can then call a method on the reference. In this example we call the open
method of the PdfDocument
component. The documentId
parameter is the document id of a document in your document collections. See the PdfApplication.getDocuments
call for more information on how to get the list of all documents.
ts
pdfDocument.current.open(documentId);
Screenshot
Code
tsx
import {
IPdfDocument,
PageMode,
PdfApplication,
PdfDocument,
PdfPages,
defineCustomElements,
} from "@tallcomponents/unopdf-react";
import { useEffect, useRef, useState } from "react";
defineCustomElements();
// Note: this example uses Vite and retrieves the keys from the environment.
// This should not be used in production.
// See the authentication section in the usage guide for more information.
const publickey = import.meta.env.VITE_PUBLIC_KEY;
const privatekey = import.meta.env.VITE_PRIVATE_KEY;
function App() {
const [documents, setDocuments] = useState<IPdfDocument[]>([]);
const pdfApplication = useRef<HTMLPdfApplicationElement>(null);
const pdfDocument = useRef<HTMLPdfDocumentElement>(null);
useEffect(() => {
// Once we have an application retrieve the list of documents
if (pdfApplication.current) {
pdfApplication.current.getDocuments().then((documents) => {
setDocuments(documents);
});
}
}, [pdfApplication]);
useEffect(() => {
// if and once we have documents open the first one
if (pdfDocument.current && documents.length > 0 && documents[0].id) {
pdfDocument.current.open(documents[0].id);
}
}, [pdfDocument, documents]);
return (
<>
<h1>UnoPdf Example: Display Document in React</h1>
<PdfApplication
ref={pdfApplication}
publickey={publickey}
privatekey={privatekey}
/>
<PdfDocument ref={pdfDocument} />
<PdfPages pageMode={PageMode.Single} />
</>
);
}
export default App;
Running the example
- Download the react - Opening and displaying a document project
- Unzip the file to a directory
react-display-document
.shellunzip react-display-document.zip -d react-display-document
- Open a terminal and go to that directoryshell
cd react-display-document
- Install dependenciesshell
npm install
shellyarn
- Start the projectshell
npm run start
shellyarn start