Friday, November 15, 2024
Google search engine
HomeLanguagesHow to open PDF file in new tab using ReactJS ?

How to open PDF file in new tab using ReactJS ?

ReactJS is a popular JavaScript library used for building user interfaces. When working with PDF files in a React application, you may come across a requirement to open a PDF file in a new tab or window on a click of button. In this article, we’ll explore how to achieve this using ReactJS. 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

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”.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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments