Sometimes, we want to open PDF when clicking on a link with React.
In this article, we’ll look at how to open PDF when clicking on a link with React.
How to open PDF when clicking on a link with React?
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.
Conclusion
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.