react-pdf
react-pdf copied to clipboard
usePdf Cannot read properties of null (reading 'props')
Package version: 2.0.20
When using usePdf hook, while gendering the PDF an error gets thrown.
Error message:
TypeError: Cannot read properties of null (reading 'props')
Stack track leads to:
- react-pdf.browser.es.js
props = container.document.props || {};
In the code itself I see define above:
var container = {
type: 'ROOT',
document: null
};
And accessing props on null can result in such an error.
The result is that for a split of second the instance.error returns an error which can be misleading for the user if we check for that property to show an error and after ±half a second the file gets generated and rendered successfully.
Same here, for me it happens when I initially have a document = null and then set it later (using a useMemo + update)
const document = useMemo(
() =>
Boolean(isEnabled) ? (
<CustomDocument />
) : null,
[isEnabled]
);
const [instance, update] = usePDF({ document });
useEffect(() => {
if (document) {
update();
}
}, [document]);
EDIT: a quick fix for me was to replace the fallback : null
by : <Document />
The same happened to me. This creates a bad UX because we just end by deciding on not to use the error object, as it will confuse users.
Instead of doing this:
<PDFDownloadLink
document={<PDF />}
fileName={"file.pdf"}
>
{({ blob, loading, url, error }) => {
return error
? "Please, try again"
: loading
? "Loading..."
: "Download";
}}
</PDFDownloadLink>
I had to do this:
<PDFDownloadLink
document={<PDF />}
fileName={"file.pdf"}
>
{({ blob, loading, url }) => {
return loading
? "Loading..."
: "Download";
}}
</PDFDownloadLink>
Which is bad. I wish I could better handle the error.
Where isEnabled comes from?
if you face this issue when trying to test your code , put this code in setup file :
jest.mock('react-native-blob-util', () => { return { DocumentDir: () => {}, polyfill: () => {}, }; });