This mundane task fairly simple on static views, isn't complying with React.
Can someone advise me how to open a pdf file as a href on a new tab?
Here's my code using react-bootstrap and react-router:
<NavDropdown eventKey={3} title="Forms">
<MenuItem eventKey={3.1} href="https://www.google.com/" target="_blank">Form 1</MenuItem>
<MenuItem eventKey={3.2} href="samba.pdf" target="_blank">Form 2</MenuItem>
</NavDropdown>
The external link to google works fine.
The pdf (saved on same level directory as the code above) doesnt.
When I click on the pdf link it redirects me to my "404 catch all" route.
<Switch>
<Route path="/" exact component={Home} />
<Route path="/contact" exact component={Contact} />
<Route path="/about" exact component={About} />
<Route component={NotFound} />
</Switch>;
EDIT: Solution here: answered by Link_Cable
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. 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.
The easiest way to put PDF in an HTML document is using the <a> tag with its href attribute. You need to add the URL or the reference link of your PDF file to the element. Your code will look like the following.
Place the pdf into a folder in /src. Import it like a component. Set href
parameter as the imported pdf and the target = "_blank"
.
import React, { Component } from 'react'; import Pdf from '../Documents/Document.pdf'; class Download extends Component { render() { return ( <div className = "App"> <a href = {Pdf} target = "_blank">Download Pdf</a> </div> ); } } export default Download;
I had to make a function to open the pdf in the new tab actually :D
import Pdf from "../../documents/resume.pdf";
onResumeClick() {
window.open(Pdf);
}
render() {
return (
<a onClick={this.onResumeClick}>
Resume
</a>
)}
Also you can use require
function directly:
import React, { Component } from 'react';
class Download extends Component {
render() {
return (
<div className="App">
<a href={require('../Documents/Document.pdf')} target="_blank">Download Pdf</a>
</div>
);
}
}
export default Download;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With