Search code examples
reactjstypescriptreact-pdf

react-pdf library is not loading the PDF document


I'm using react-pdf library to display the PDF file.

but the library is not loading the the file, even it is not giving any error messages.

import React from "react";
import { Document, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;

const Dashboard = (): React.ReactElement => {
  const [file, setFile] = React.useState("./invoice.pdf");
  function onFileChange(event: any) {
    console.log(event.target.files);
    setFile(event.target.files[0]);
  }
  function onDocumentLoadSuccess(params: any) {
    console.log("LOAD Success ", params);
  }
  return (
    <React.Fragment>
      <Box minHeight="500px">
        <Document
          file={file}
          onLoadSuccess={onDocumentLoadSuccess}
        ></Document>
      </Box>
      <input onChange={onFileChange} type="file" />
    </React.Fragment>
  );
};

export default Dashboard;

Any kind of help will much be appreciated, Thanks!


Solution

  • You need to use Page component as well. See the working demo https://codesandbox.io/s/stackoverflow-69097706-react-pdf-demo-s2zmc

        
         <Document
           file={file}
           onLoadSuccess={onDocumentLoadSuccess}
         >
        {/* This is needed to fix the issue */}
        <Page pageNumber={1} /> 
        </Document>