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

前端 未结 6 598
感情败类
感情败类 2021-01-04 00:19

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

相关标签:
6条回答
  • 2021-01-04 00:47

    Client side only? So there is no web server to host your web site? If you have a webserver then you could return the raw pdf content content back to the browser as "application/pdf" content type. Client side only would be to specify a relative path like

    <a href="../FolderName/samba.pdf"> 
    
    0 讨论(0)
  • 2021-01-04 00:54

    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;
    
    0 讨论(0)
  • 2021-01-04 00:57

    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;
    
    0 讨论(0)
  • 2021-01-04 00:58

    I placed the following in the header of the component I needed it in. The document was stored in Documents folder under src.

    import Pdf from '../Documents/doc.pdf';
    

    And then used the imported document in the tag using href.

    <a href = {Pdf}>Resume</a>
    

    Worked for me!

    0 讨论(0)
  • 2021-01-04 01:02

    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>
    )}
    
    0 讨论(0)
  • 2021-01-04 01:08

    I have solved that by creating _someFolder in the public folder and then in the component:

    import {pdfFile} from "/_someFolder/pdfFile.pdf";
    
    ....
    
    <div className="headerProfile-menu-list" onClick={() => window.open(pdfFile)}><i className="mdi mdi-help-circle"></i> Help</div>
    
    ....
    

    that prevent by adding hashes to the filename when serviceWorker is used.

    0 讨论(0)
提交回复
热议问题