3

Is there a way to get all root elements in React?

I have a situation where elements are being created at the root via ReactDOM.render, however they are not being unmounted when my component unmounts.

I would like to get all elements, other than AppContainer and then unmount them when my component upmounts, is this possible?

enter image description here

user3284707
  • 3,033
  • 3
  • 35
  • 69
  • What's the relationship between AppContainer and other components? The question lacks https://stackoverflow.com/help/mcve that could explain what's going on. – Estus Flask Oct 02 '18 at 15:42
  • I am adding custom react components to a datatable, I am confused at why they are going in at the root, as they should be going in under the td. – user3284707 Oct 02 '18 at 15:58
  • as per this example ... https://stackoverflow.com/a/44204235/3284707 – user3284707 Oct 02 '18 at 15:59
  • You need to keep track of them and unmount manually with unmountComponentAtNode when they should be unmounted. I cannot say how this should be done in your case because you didn't show your own code. The question you've linked uses jQuery, while you likely not. MCVE is a requirement for SO questions because even if you think your case is the same as in another question, it may differ. – Estus Flask Oct 02 '18 at 16:39

1 Answers1

4

root components rendered with ReactDOM aren't aware of each other.

to unmount a component not in the tree of an unmounting component, you could do something along these lines:

const App1Component = <div>app1</div>;
const app1 = document.getElementById("app1")
ReactDOM.render(<App1Component/>, app1);

export class AppContainer extends React.Component {
  componentWillUnmount() {
    // ummount other components not in this tree
    if (app1) 
      ReactDOM.unmountComponentAtNode(app1);
  }
}

basically, whenever your 'main' component is unmounting, call ReactDOM.unmountComponentAtNode with your other root elements DOM nodes.

Uzi
  • 2,436
  • 13
  • 13
  • Thanks for your answer, I am not sure how I can accomplish this, as the elements are created dynamically when the datatable is created, as per the link stackoverflow.com/a/44204235/3284707 therefore I do not have a refernece to the td values when the component unmounts? – user3284707 Oct 02 '18 at 16:16
  • well, technically, you could try obtain their ref using `getElementById`. a better way would be to assign a react ref to each root element's DOM node. – Uzi Oct 02 '18 at 16:30