简体   繁体   中英

React - Import dynamically path to pdf file

Firstly, my page will make an http request to an API

API then response an object which have a path: ./assets/sample.pdf

I want to get urlPdf from import urlPdf from response.path

How can I do that ?

I'd try with https://www.npmjs.com/package/react-pdf

import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';

const App = () => {
  const [pageNumber, setPageNumber] = useState();
  const [numPages, setNumPages] = useState();
  const [urlPdf, setUrlPdf] = useState();

  const _onDocumentLoadSuccess = ({ numPages }) => setNumPages(numPages);
  
  const fetchPdfPath = ({
    // logic handle get path...
    // setUrlPdf(response.data);
  })
  
  return (
    <div>
      {urlPdf && (
        <Document
          file={urlPdf}
          onLoadSuccess={_onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
      )}
      <p>Page {pageNumber} of {numPages}</p>
    </div>
  );
}

Oh super simple. Just const result = require(response.path)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM