Skip to content
Home » Blogs » How To Build a Document Viewer in Next.js

How To Build a Document Viewer in Next.js

Wooden desk with documents, laptop, and coffee cup creating a modern office atmosphere.

This quick guide will show you how to display the preview of a document using react-documents package in a Next.js application.

Steps

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

You will see the following line in your package.json file.

"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:

Upon save, 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 previewer.

You can enhance the look and feel of the page by adding a few styles.

Conclusion

This guide talked about how to display a document viewer in a Next.js app.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *