This guide will show you how to display a document viewer component using react-documents
package in a Nextjs application.
With this package, you can show the following types of documents:
- ppt
- pptx
- doc
- docx
- xls
- xlsx
Let’s start.
Steps to create a Document Previewer
1. Create a Next.js project
Open a text editor of your choice (I use VS Code) and type the following command in the terminal:
npx create-next-app@latest
Follow the instructions and a new Next.js app will be created.
You can run the app with npm run dev and go to http://localhost:3000 to see your application.
2. Install react-documents package
Install the react-documents package with this command:
npm i react-documents
Now, in your package.json
file, the following line will be added:
"react-documents": "^1.2.1"
3. Add the code for document preview
Copy the code below into the page.js
file present in this path: app\page.js
<DocumentViewer queryParams="hl=Nl"></DocumentViewer>
Do not save just yet as it will throw a runtime error.
To prevent this error, paste the code below on the top of your page.js
file:
"use client";
Now, code will look like this:
If you save now, this is how your project will look like on the browser.
This is because we did not add the location or the URL of the document, so nothing can be previewed.
4. Add a document URL
You can use this PDF URL:
https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
Now, add the code below to the DocumentViewer component.
url="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
Now, code will be like this:
5. Final result
Save the project and check the browser. The PDF will be displayed on the viewer component.
You can enhance the look and feel of the page by adding a few styles.
Conclusion
This guide talked about how to display a component for document viewer in a Nextjs app with the help of react-documents package. Likewise you can follow the same procedure for React.
Additionally, you can use one more package called React PDF Viewer for displaying just PDFs on the Nextjs/React application.