If you want update your single page PDF Viewer to show all pages and scroll through all of them, these are my changes
I had to change a PDF viewer from showing a single page to showing the full set of pages and be scrollable, so I had the code already for showing the one page, and to show all the pages each page needed to have it's own canvas, and because I am creating my canvas using the useRef() hook, I couldn't just put it in a function that will loop and create a canvas when it was building the pdf pages to be viewed. This is the error I kept getting when I used that hook in a function:.
Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons: 1. You might have mismatching versions of React and the
renderer (such as React DOM) 2. You might be breaking the Rules of
Hooks 3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.
Also, the other obstacle I had was when the const canvasRef = useRef(null) was created, the object looked like this when I needed it to be ready to hold page data: {current: null}. So there was a timing issue, I needed to have the DOM ready in that area of the react page before the canvasRef would blossom to a full canvas object, so I created a state hook to let me know when the DOM is ready, then kick off all the functions to render the pages for the PDF. Note, there was a renderPage function that took a pdfJs object, after my updates it took the pdfJs, the page number and the created canvas for that PDF page.
Here are my code snippets:
const canvasRef = useRef(null);
const canvasRefs: any[] = useMemo(() => {
const tempRefs: any[] = []
for(let i = 0; i < 4; i++) {
tempRefs[i] = { ...canvasRef}
}
return tempRefs;
}, [])
useEffect(() => {
if (canvasRefs[0]?.current) {
setIsDomReady(true);
}
});
useEffect(() => {
if (isDomReady && pdfJs) {
for(let i = 0; i < numPages; i++) {
renderPage(pdfJs, canvasRefs[i].current, i+1);
}
}
}, [pdfJs, isDomReady]);
const renderPage = async (pdfJs, canvas, pgNumber) => { ...