Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - How to open PDF file as a href target blank

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

like image 361
Jonca33 Avatar asked Feb 01 '18 22:02

Jonca33


People also ask

How do I show a PDF link in 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. 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.

How do I open HREF in PDF?

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.


3 Answers

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; 
like image 70
Erik Martín Jordán Avatar answered Oct 07 '22 08:10

Erik Martín Jordán


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>
)}
like image 37
Hung Vinh Ngo Avatar answered Oct 07 '22 07:10

Hung Vinh Ngo


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;
like image 44
Erik P_yan Avatar answered Oct 07 '22 07:10

Erik P_yan