React-pdf: react ref={} calls three times, custom callbacks not helpful enough

Created on 23 Jan 2018  ·  4Comments  ·  Source: wojtekmaj/react-pdf

Hi there,

maybe I misunderstand something but for some reason when I use ref like that

<Document
  file={file}
  onLoadSuccess={this.onDocumentLoadSuccess}
  ref={node => console.log(node)}
>
....

I see three times following output:

screenshot 2018-01-23 17 13 23

Well, I want to use ref to detect where it has been rendered on the page (offsetTop, offsetLeft etc) and there is no other way to get it except using ref, so my question is it ok that it's invoking three times?

In my real example I load the file from client side, but still, I have the same issue :(

P.S. The code is taken from sample folder of your repository

enhancement question

All 4 comments

Hey @nnnikolay,
yes, this is entirely normal behavior of any component (mind you - component, not element) React updates.

Besides, it is a very bad idea to check whether the page has been rendered using Document component's ref.

The only method I can recommend is onRenderSuccess prop callback placed in Page component you'd want to listen for successful render to.

You can also do that by attaching inputRef prop to Page component, which will pass your ref function to the root div element rendered by Page component. However, this method is discouraged because starting with 3.0.0, a Page root div will appear earlier than before to allow easier styling while the page is in loading/rendering state.

Thanks @wojtekmaj for replying and for ideas, first of all, as I see onRenderSuccess does not take any argument so it's not clear how in this callback I can find out Page DOM Node position on the page, I would be glad to hear your advice in that.

Nevertheless, inputRef is ok for me, because I just need to know where the <div> is rendered (top and left coordinates) on the page.

Ah, right. onRenderSuccess should actually give more info about what it renders.

Currently, you can do a workaround (code simplified for readibility):

const pageNumber = 1;

return (
  <Document>
    <Page
      pageNumber={pageNumber}
      onRenderSuccess={() => doSomething(pageNumber)}
    />
  </Document>
);

but I fully agree about that. Improvements to callback functions land on my list for 3.0! :)

Improvements were just merged and will be first available in incoming v3.0.0-alpha.3.

Was this page helpful?
0 / 5 - 0 ratings