Categories
React Answers

How to open PDF when clicking on a link with React?

Spread the love

To open PDF when clicking on a link with React, we can import the PDF file as a module and set that as the value of the href prop.

For instance, we write:

import React from "react";
import pdf from "./dummy.pdf";

export default function App() {
  return (
    <div>
      <a href={pdf} target="_blank" rel="noreferrer">
        Download Pdf
      </a>
    </div>
  );
}

We set the href prop of the a element to pdf which we imported with import.

Then we set the target prop to '_blank' to open the PDF in a new window.

We also have rel="noreferrer" to make sure that no referrer info is leaked when the link is clicked.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.