React: componentDidMount, there is no guarantee that the DOM node is in the document?

Created on 5 Mar 2017  路  3Comments  路  Source: facebook/react

I read the source code and find the comment of componentDidMount method.

Invoked when the component has been mounted and has a DOM representation.
However, there is no guarantee that the DOM node is in the document.

what's the meaning of there is no guarantee that the DOM node is in the document.?

Most helpful comment

Ref callback won't help you either. React manages the DOM with respect to the container you pass. So from React's point of view, the moment the DOM is attached to the container, React's job is done.

React can't know when that node will be attached to the document. This is something your code is doing, and thus has control over.

You could attach it before calling React, and then you'd always be "in the document" by the time componentDidMount or ref callback fires.

Or you could attach it later (as I imagine you're doing). In that case you are the one who knows when it gets attached (because you do the attaching) so the best way is to add your own callback queue that you'll notify when you attach the container.

Hope this helps.

All 3 comments

With this code:

var div = document.createElement('div');
ReactDOM.render(<MyComponent />, div);

The componentDidMount would fire because the mounting has happened. However, as you can see, the div I鈥檓 mounting into is not actually part of the page鈥檚 DOM. Therefore, the component鈥檚 DOM node is also not in the document even though it has mounted into its container.

You can use document.body.contains(node) to check if something is in the document or not.

@gaearon is there best-practice documentation somewhere for code that runs in componentDidMount that needs the node to be attached to the document? e.g. it seems setTimeout is probably not the right approach in there :) Should such actions be taken in a ref callback instead?

Ref callback won't help you either. React manages the DOM with respect to the container you pass. So from React's point of view, the moment the DOM is attached to the container, React's job is done.

React can't know when that node will be attached to the document. This is something your code is doing, and thus has control over.

You could attach it before calling React, and then you'd always be "in the document" by the time componentDidMount or ref callback fires.

Or you could attach it later (as I imagine you're doing). In that case you are the one who knows when it gets attached (because you do the attaching) so the best way is to add your own callback queue that you'll notify when you attach the container.

Hope this helps.

Was this page helpful?
0 / 5 - 0 ratings