Displaying PDF in React app (2024)

Displaying PDF in React app (3)

I want to show you an easy and simple way to display PDF files using React in the browser. I will be using a library called react-pdf. This library is capable of rendering PDF files given an URL or a local file inside the project or base64 encoded version.

To get started, create a simple React application using Create React App. To do this you can run the following commands:

npx create-react-app display-pdf-app
cd display-pdf-app
npm start

After this, add the react-pdf library to the project using the following command:

npm install --save react-pdf 

To render the PDF file, react-pdf has a Document component where you need to pass a file prop. Then inside the Document component, you need to create a Page component. Simple isn’t it? Sample code:

import React from 'react';
import { Document, Page } from 'react-pdf';

import samplePDF from './test.pdf';

export default function Test() {
return (
<Document file={samplePDF}>
<Page pageNumber={1} />
</Document>
);
}

The final project structure will look like this:

Displaying PDF in React app (4)

Let’s start with creating single-page.js and all-pages.jsinside the components -pdf folder with the following contents:

  • single-page.js

Now navigate to App.js and replace the content with the following code:

Displaying PDF in React app (2024)
Top Articles
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 6384

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.