I would need smooth scrolling down to component with generated pdf. But it looks like that first is scrolled to view and then component is mounted. How can I set waiting to component is displayed and then scroll to view this component? When I click to button, the pdf will start to generate. After generating this pdf, I would like scroll to view this PDFViewer.
My solution does not work. 'await' has no effect on the type of this expression. OR Object is possibly 'null'.
I use reactjs 17.0.2, react-pdf/renderer 3.0.1, typescript.
Code:
import { PDFViewer } from "@react-pdf/renderer";
export const Print: NextPage = () => {
const [pdfGenerationEnabled, setPdfGenerationEnabled] = useState<boolean>(false);
const generatePDFAndView = async () => {
setPdfGenerationEnabled(true);
await document.getElementById("generated-pdf-view")?.scrollIntoView({ behavior: "smooth" });
}
return (
<DownloadAndPrint>
<h2>Generating PDF</h2>
<p>
Some long text
Some long text
Some long text
.
.
.
</p>
<Button
className="btn-generate-pdf"
onClick={() => { generatePDFAndView() }}
>
Vygenerovať pdf súbory
</Button>
{pdfGenerationEnabled
?
<>
<div id="generated-pdf-view" className="viewer-styled">
<PDFViewer showToolbar={true} style={{ height: "45vh", width: "100%" }}>
<ComponentPrint
data={data}
/>
</PDFViewer>
</div>
</>
: ""
}
</DownloadAndPrint>
);
};
EDITED: After added delay, it's works. After 3 seconds smooth scrolled to the pdf viewer. But I don't know how many seconds it should waiting? Sometimes generated pdf has 3 pages, sometimes 300 pages. According to the data.
const delay = (n) => new Promise(r => setTimeout(r, n*1000));
const generatePDFAndView = async () => {
setPdfGenerationEnabled(true);
await delay(3.0); // waiting 3s
document.getElementById("generated-pdf-view")?.scrollIntoView({ behavior: "smooth" });
}