Morgana
Morgana

Reputation: 337

Open link (.pdf file) in new tab after running function and without changing route

In my react app I need to show a pdf file in a new tab, after running a function which returns the path of the file.

What I was doing until now was using a simple div with an onClick event which triggered the above function and when I got the path of the file from the back end, I was using this.props.history.push(/'PDF') and pushing to the PDF component, which by the way is this:

 render() {
    return (
        <Iframe
          url={`${process.env.REACT_APP_NODE_SERVER}/${this.props.PDFFilename}`}
          position="absolute"
          width="100%"
          id="myId"
          height="100%"
          />
    );
  }

I've also used react-new-window which works fine, it does open the pdf component in a new window but since I still use this.props.history.push, react app still changes the routing which is not desirable.

Then, I used Link component (from react-router-dom). The problem here is that the link gets triggered before the function gets run, ending in an empty new tab. This is how I used the link component:

<Link to=/PDF target="_blank">
<img className="print-dropdown" src={print} alt="print" />
<span onClick={() =>
   printCons(
     this.props.username,
     this.props.password,
     "A4",
     this.props.consignmentNo,
     this.props.updatePDFFilename,
    )
   }
>
  A4
 </span>
</Link>

Any suggestion would be much appreciated.

Upvotes: 0

Views: 1064

Answers (1)

Marcus Ilgner
Marcus Ilgner

Reputation: 7211

Why not just use Window.open()? Once you have the URL of the file, you can just open it in a new window without pushing any state or otherwise having to do anything React-specific.

Upvotes: 1

Related Questions