I'm using react-pdf-viewer to display articles I've written. I have a modal component named "PDFModal" that uses a portal to display the modal containing the PDF. The issue I'm having is that I need each pdf to open to the page where my article starts, but when I pass the value as a prop, it doesn't work. I also tried creating a piece of state for this, but it's still not setting the initialPage correctly.
The modal is at root level
<body>
<div id="root"></div>
<div id="modal"></div>
<div id="PDFModal"></div>
</ body>
Here's PDFModal:
export default function PDFModal({ fileUrl, open, onClose, startPage }) {
if (!open) return null;
const defaultLayoutPluginInstance = defaultLayoutPlugin();
return ReactDom.createPortal(
<>
<div style={OVERLAY_STYLES} />
<div style={MODAL_STYLES}>
<button style={BUTTON_STYLES} onClick={onClose}>
Close
</button>
<Worker workerUrl="https://unpkg.com/[email protected]/build/pdf.worker.min.js">
<Viewer
fileUrl={fileUrl}
plugins={[defaultLayoutPluginInstance]}
defaultScale={SpecialZoomLevel.ActualSize}
initialPage={startPage} <--- This value isn't being set correctly
If I console log the value startPage, it's correct....
/>
</Worker>
</div>
</>,
document.getElementById("PDFModal")
);
}
Here's the calling page:
export default function Articles() {
const [isOpen, setIsOpen] = useState(false);
const [startPage, setStartPage] = useState(5); <- Assigning a value of 5. I also tried using just props because it's a 1 way data flow, but that didn't work either.
return (
<div className="articles">
<h1>Articles</h1>
<div className="articles-card-container">
<div className="card">
<div
style={BUTTON_WRAPPER_STYLES}
onClick={() => console.log("clicked")}
>
<button onClick={() => setIsOpen(true)}>
3 Weird Ways to Increase Production and Reduce Breakage
</button>
</div>
<PDFModal
fileUrl={ThreeWeirdWays}
open={isOpen}
onClose={() => setIsOpen(false)}
startPage={startPage} //I called it startPage on this side....
></PDFModal>
</div>
</div>
</div>
</div>
);
}
I have a feeling that it's because the insertion point is outside of "root" which is where the Articles.js page resides. So the modal isn't a child of the articles page.
I found out what the issue was.
It's not that the initialPage value isn't correct or being picked up by the viewer.
The problem is that when the PDF modal is launched, ALL PDF Modals on the entire page are looped through. I only set the initialPage on the first one, so as it looped through it picked up the initial page the first time, but never again.
I found this by noticing the PDF being loaded wasn't correct either. The pdf being loaded was the last one in my list of imported PDFs.
So case close. Now I need to figure out how to keep it from reading all of them.