Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unmount all root level components in ReactJs

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

like image 831
user3284707 Avatar asked Sep 12 '25 13:09

user3284707


1 Answers

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.

like image 140
Uzi Avatar answered Sep 14 '25 03:09

Uzi