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.
![The Nextjs app on http://localhost:3000](https://miro.medium.com/v2/resize:fit:875/1*1GkfMdssM4v6lH2GThYB8g.png)
2. Install react-documents package
![react documents home page on npm](https://miro.medium.com/v2/resize:fit:875/1*Nd8xTjWg7Q3hz1cAdkl84w.png)
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.
![](https://miro.medium.com/v2/resize:fit:875/1*T_4SH25s14AW4eLBnUv_SA.png)
To prevent this error, paste the code below on the top of your page.js
file:
"use client";
Now, code will look like this:
![](https://miro.medium.com/v2/resize:fit:875/1*MhPoeqS76xYtoVkkOJYFPg.png)
If you save now, this is how your project will look like on the browser.
![](https://miro.medium.com/v2/resize:fit:875/1*rGa-XLfuSeDA1kc0j363MQ.png)
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:
![](https://miro.medium.com/v2/resize:fit:875/1*xm1CUjakPZ_lFLgg_iTD8w.png)
5. Final result
Save the project and check the browser. The PDF will be displayed on the viewer component.
![Screenshot of the document viewer in Nextjs](https://miro.medium.com/v2/resize:fit:875/1*AsNxveVi4FS19YoEFnzRJA.png)
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.