Skip to content
Related Articles

Related Articles

How to open PDF file in new tab using ReactJS ?

View Discussion
Improve Article
Save Article
  • Last Updated : 04 Aug, 2022
View Discussion
Improve Article
Save Article

This article is related to opening a PDF file in a new tab in the web browser in React.js on a click of button. It is possible by importing a PDF file as a module in your file.

Approach: To accomplish this task we do not need to create any new component, we will use one single component named “App.js” which will by default be available when we create React application. In “App.js” we will write our main logic to accomplish the given functionality. To achieve this task we do not need to install any external module.

Setting up React.js application:

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: The project structure will look like this:

 

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

App.js




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”.Now, click on the links you created.

 

Explanation: You will notice that both links will open in new tabs with their particular PDF files, both the pdf files are distinct.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!