Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

componentDidMount, there is no guarantee that the DOM node is in the document? #9117

Closed
mrdulin opened this issue Mar 5, 2017 · 3 comments
Closed

Comments

@mrdulin
Copy link

mrdulin commented Mar 5, 2017

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.?

@gaearon
Copy link
Collaborator

gaearon commented Mar 5, 2017

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’m mounting into is not actually part of the page’s DOM. Therefore, the component’s 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 gaearon closed this as completed Mar 5, 2017
@craigkovatch
Copy link

@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?

@gaearon
Copy link
Collaborator

gaearon commented Aug 8, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants