wojtekmaj / react-pdf

Display PDFs in your React app as easily as if they were images.
https://projects.wojtekmaj.pl/react-pdf
MIT License
9.11k stars 867 forks source link

A <Page/> component with a pdf prop causes an error if it is not inside a <Document/> component #1709

Closed MKisil closed 6 months ago

MKisil commented 6 months ago

Before you start - checklist

Description

I need to display the pages of several pdf documents in one common block. The <Document/> component places the pages of each pdf file in a separate block.

In the documentation I read the following:

Displays a page. Should be placed inside . Alternatively, it can have pdf prop passed, which can be obtained from 's onLoadSuccess callback function, however some advanced functions like linking between pages inside a document may not be working correctly.

That is, as far as I understood,<Page/> can not be wrapped in <Document/>, but simply transfer pdf props.

But when I try to display the page like this -

 <Page 
     pdf={pdf}
     otherProps
 />

Then I get the following error -Invariant failed: Unable to find Document context. Did you wrap <Page /> in <Document />?

I get the pdf props in the onLoadSuccess function: onLoadSuccess={(pdf) => onDocumentLoadSuccess(pdf, otherArguments)

But for example, if you do it like this:

<Document file={testPdf1}>
    <Page
        pdf={testPdf2}
        pageNumber={1}
    />
</Document>

testPdf1 I just import into the app: import testPdf1 from './test.pdf' testPdf2 I get from the onLoadSuccess callback.

Then everything will work and page 1 will be displayed from testPdf2.

Steps to reproduce

Try this code to reproduce the error:

import {Document, Page} from "react-pdf";
import {useState} from "react";
import yourPDF from './yourPDF'

function SomeComponent() {
    const [pdf, setPdf] = useState();

    function onDocumentLoadSuccess(pdf) {
        setPdf(pdf)
    }

    return (
        <div>
            <Document
                file={yourPDF}
                onLoadSuccess={(pdf) => onDocumentLoadSuccess(pdf)}
            />

            <Page
                pdf={pdf}
                pageNumber={1}
            />
        </div>
    )
}

Expected behavior

A <Page/> component with a pdf prop is expected to work without a <Document/> wrapper

Actual behavior

An error occurs: Invariant failed: Unable to find Document context. Did you wrap <Page /> in <Document />?

Additional information

No response

Environment

wojtekmaj commented 6 months ago

Yep, that's definitely a regression and you're doing everything right. Thanks for reporting.