Unmount all root components from container
See original GitHub issueHi,
I’m using React for certain modules in a mature project which is primarily built around jQuery and server-side rendered HTML. The main routing mechanism loads a particular URL via $.ajax
and then replaces the HTML of the content container of the page via $('#content).html(result)
.
When using React components on a page I noticed that I manually have to unmount the root components before leaving the page and loading a new page with $('#content).html(...)
. In that case the React components are rendered into a div
deeply nested somewhere in the ‘#content’ container.
Unmounting the root components rendered into the content container manually via React.unmountComponentAtNode
works as expected. But I’m concerned that developers could forget to unmount their components which could lead to memory leaks and unexpected behavior I guess.
Therefore I would like to unmount all possible root components in a generic way directly from the router. Unfortunately I don’t know how to get all the DOM nodes from a particular parent container in a generic way.
This doesn’t work because the components are not rendered directly into the content container but somewhere in the content container hierarchy:
React.unmountComponentAtNode(document.getElementById("content"));
Is there any way to retrieve all root components for a given DOM element? Selecting all elements with data-reactid
would not only select the root components but also child components.
It would be helpful if React would directly support unmounting of a whole container.
Thanks in advance for your help and keep up the good work!
Benjamin
Issue Analytics
- State:
- Created 8 years ago
- Comments:6 (4 by maintainers)
This is doable in userland but it’s definitely awkward and requires some tree search to find all roots (or overselecting nodes -
qSA('[data-reactid']
and check each for!node.parentNode.dataSet['reactid']
).It might be handy to expose roots in same way, this has come up before in other tooling. But it’s awkward to do. cc @sebmarkbage
So what I might suggest for you is an imperative wrapper around React.render - basically have something that tracks when you call render, store a reference to the target node, and then you can call into that to unmount. Here’s a really simple way you could do it.
We actually use a very similar pattern at FB. I suspect that @sebmarkbage or @spicyj will probably close this and suggest something what I did.
@winterbe React blog post will appear here: http://facebook.github.io/react/blog/