Enable navigation through pages using react-pdf when showing multiple pages

Viewed 289

I'm using react-pdf v5.6.0 with reactjs. I tried looping through pages to show multiple pages of a pdf file at once. This is the way I've done it:

{Array.apply(null, Array(numPages))
    .map((x, i) => i + 1)
    .map(page =>
        <Page scale={scale} key={`page_${page}`} id={`page_${page}`} pageNumber={page} />
    )
}

I tried using id to navigate between them with links but the problem is the id property is never added to the rendered output. Is there anyway you can suggest to enable navigation through pages while showing multiple of them at once? Is this even possible via react-pdf?

1 Answers

I have used ref's to scroll to specific page when user clicks on a next/prev button

const [numPages, setNumPages] = useState(null);
  
  const pageRefs = React.useRef({});
  const isFirstPage = pageNumber === 1;
  const isLastPage = pageNumber === numPages
    
  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }

  const goToPreviousPage = () => {
    if (!isFirstPage) setPageNumber(pageNumber - 1);
    pageRefs.current[pageNumber - 1].scrollIntoView({ behavior: "smooth" });
  };

 
      <div className="pdf__container">
          <Document file={pdf} onLoadSuccess={onDocumentLoadSuccess}>
            {[1, 2, 3, 4].map((page, i) => (
              <div
                key={i}
                ref={(el) => {
                  pageRefs.current[page] = el;
                }}
              >
                <Page
                  className="pdf__page"
                  width={400}
                  scale={2}
                  pageNumber={i + 1}
                />
              </div>
            ))}
          </Document>

          <button
          id="next-page-icon"
          type="arrow-up-circle"
          onClick={goToPreviousPage}
          size="16"
        ></button>
        </div>
Related