How to open PDF file in new tab using ReactJS ?
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 in new tab using React JS we will be using the HTML anchor tag. We will pass the pdf url to href and use target _blank. It will open the file in a new tab on the provided URL.
Steps to Create React 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 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:
// Filename - 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”