Reputation: 3259
I'm using react-pdf (github link) to display a pdf on my react app. This is the code:
import { useColor } from '@/hooks';
import { ArrowLeftIcon, ArrowRightIcon } from '@chakra-ui/icons';
import { HStack, Spinner, Text, VStack } from '@chakra-ui/react';
import React, { useState } from 'react';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
enum Direction {
Left = '-',
Right = '+',
}
function PdfComponent({ pdfLink }) {
const { primary } = useColor();
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
function onDocumentLoadSuccess({ numPages }) {
setNumPages(numPages);
}
const turnPage = (direction: Direction) => {
if (direction === Direction.Left) {
if (pageNumber === 1) return;
setPageNumber(pageNumber - 1);
}
if (direction === Direction.Right) {
if (pageNumber === numPages) return;
setPageNumber(pageNumber + 1);
}
};
return (
<VStack>
<Document file={pdfLink} onLoadSuccess={onDocumentLoadSuccess} loading={<Spinner />}>
<Page pageNumber={pageNumber} />
</Document>
<HStack>
<ArrowLeftIcon cursor="pointer" color={primary} onClick={() => turnPage(Direction.Left)} />
<Text>
Page {pageNumber} of {numPages}
</Text>
<ArrowRightIcon cursor="pointer" color={primary} onClick={() => turnPage(Direction.Right)} />
</HStack>
</VStack>
);
}
export default PdfComponent;
Everything works fine except for the fact that when I turn the page (if the page has never been seen) the browser scroll the window up, like during a reload, and I have to scroll down to see the entire pdf again. Once I turn all the pages of the pdf, then this behaviour stops and I can easily change the pages and the window stay focues on the pdf component.
How can I fix this?
Upvotes: 0
Views: 4223
Reputation: 22577
It seems React will scroll viewport to the top when components change dimensions on the page. Solution is to set height
on the CSS class - .react-pdf__Document
of the container Document. height
attribute should not be in %
, use other metric like px or vh, this should work -
.react-pdf__Page.prevPage {
position: absolute !important;
z-index: 1;
}
.react-pdf__Document{
height: 800px; // change height accordingly
}
Upvotes: 1