Search code examples
reactjsscrollrefreact-pdf

How to get current scrolled element key - React PDF


I need to display the current page on my ReactPDF viewer.

How can I call setPageNumber while user scrolls through Pages?

  const [pageNumber, setPageNumber] = useState(1);

  let currentRef = useRef(null);

  <Document
      onLoadSuccess={({ numPages }) => setNumPages(numPages)}
      ...
  >
      {Array.from(new Array(numPages), (el, index) => (
        <Page
          key={`page_${index + 1}`}
          pageNumber={index + 1}
          inputRef={
            pageNumber === index + 1
              ? (ref) =>
                ref && ref.scrollIntoView()
              : null
          }
        />
      ))}
   </Document>

Previously I had a button setting the current page, and when set the component scrolls into this page.

I'd like to to set the page based on the current scrolled Page instead/as well.

Thanks!


Solution

  • I'd wrap Page in a component that leverages IntersectionObserver to look for page currently visible on the page.

    This is how I'd do it:

    https://codesandbox.io/s/react-pdf-intersection-observer-90gvy