Open In App

How to open PDF file in new tab using ReactJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

React JS, a commonly used JavaScript library for building user interfaces, sometimes requires opening PDF files in a new tab or window when a button is clicked. You can make this happen by bringing the PDF file into your React application as a module.

Prerequisites:

Approach to open PDF File:

To complete this task, there’s no need to generate a new component. We’ll rely on the existing “App.js” component, which is automatically created when initiating a React application. Inside “App.js,” we’ll craft the main logic to fulfill the specified functionality. Importantly, there’s no necessity to install any external modules for this task.

Steps to Create React Application And Installing Module:

Step 1: Create a React JS application using the following command:

npx create-react-app <project-name>

Step 2: After creating your project folder, move into that directory using the following command:

cd <project-name>

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: Let’s understand the implementation through the example:

Javascript




import React from "react";
import samplePDF1 from "./SamplePDF.pdf";
import samplePDF2 from './Example2/SamplePDF.pdf';
const App = () => {
    return (
        <>
            <center>
                <h1>Welcome to Geeks for Geeks</h1>
                <h3>Click on below link to open
                    PDF file in new tab</h3>
                <a href={samplePDF1} target="_blank"
                    rel="noreferrer">
                    Open First PDF
                </a> <br></br>
                <a href={samplePDF2} target="_blank"
                    rel="noreferrer">
                    Open Second PDF
                </a>
            </center>
        </>
    );
};
  
export default App;


Steps to Run the program: To run the application execute the below command from the root directory of the project:

npm start

Output: Your web application will be live on “http://localhost:3000”

Output



Last Updated : 29 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads