Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jump to specific page with react pdf while showing all

I want to implement a simple pdf viewer in my react project. To go to the next page I want the user just to scroll. I'm using the package react pdf (https://www.npmjs.com/package/react-pdf), which just works fine for displaying all pages scrollable (as seen in this project: https://codesandbox.io/s/displaying-pdf-using-react-5d003), but the problem is that i want to jump to a specific page on page load.

I would be grateful for a working solution or a package that is able to do both of these things.

Thanks in advance

like image 255
M Huster Avatar asked Oct 27 '25 15:10

M Huster


1 Answers

We can use refs to jump to a specific page while displaying all pages.

const pageRefs = useRef({});
const onItemClick = ({ pageNumber }) =>
    pageRefs.current[pageNumber].scrollIntoView({ behavior: 'smooth' });

Call onItemClick like this in Document tag:

<Document
    file={pdfUrl}
    onLoadSuccess={onDocumentLoadSuccess}
    loading=""
    onItemClick={onItemClick}
>

Add refs to all pages with page number in Page tag:

{Array(...Array(pages))
    .map((x, i) => i + 1)
    .map(page => (
       <div key={page} ref={el => { pageRefs.current[page] = el; }}>
          <Page
              pageNumber={page}
              width={width}
              loading=""
          />
          </div>
))}
like image 176
Vijit Nagar Avatar answered Oct 30 '25 05:10

Vijit Nagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!