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

Jonca33 picture Jonca33 · Feb 1, 2018 · Viewed 32.7k times · Source

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

Answer

Erik Mart&#237;n Jord&#225;n picture Erik Martín Jordán · Apr 17, 2018

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;