I created a react js app with create-react-app
and I am trying out react-pdf
to view pdfs. the problem I have is that my code works sometimes and sometimes doesn't. when I first load the app the pdf always loads well but if i visit other links/urls on the site and then navigate to the page with the pdf, the pdf will likely fail to load on a few attempts with an error "Failed to load PDF file".
this is how i have implemented it
imports
import { Document, Page, pdfjs } from 'react-pdf/dist/esm/entry.webpack';
import { useState } from 'react';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
code implementation
function ReactPDF() {
const imageKitURL = ' https://ik.imagekit.io/kwmvfjr0r';
const pdf = `${imageKitURL}/test_files/file-example_PDF_1MB.pdf`;
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
function onDocumentLoadSuccess({ numPages }) {
setNumPages(numPages);
setPageNumber(1);
}
function changePage(offset) {
setPageNumber((prevPageNumber) => prevPageNumber + offset);
}
function previousPage() {
changePage(-1);
}
function nextPage() {
changePage(1);
}
return (
<>
<div>
<p>
Page {pageNumber || (numPages ? 1 : '--')} of {numPages || '--'}
</p>
<button type="button" disabled={pageNumber <= 1} onClick={previousPage}>
Previous
</button>
<button type="button" disabled={pageNumber >= numPages} onClick={nextPage}>
Next
</button>
</div>
{/* eslint-disable-next-line react/jsx-no-bind */}
<Document file={pdf} onLoadSuccess={onDocumentLoadSuccess}>
<Page pageNumber={pageNumber} />
</Document>
</>
);
}
i hope the question is detailed enough to explain the situation
Try to install the types with the command:
npm i -D @types/react-pdf