Remove a child component from parent dom node in react

- 1 answer

Ad

Unmount components from the same DOM element that mounted them in.

ReactDOM.render(<SampleComponent />, document.getElementById('container'));

Then we would unmount it with:

React.unmountComponentAtNode(document.getElementById('container'));

How to unmount and reattach a component to parent container if container has two or more than two components attached to it e.g.

<div id="container">
   <SampleComponent1/>
   <SampleComponent2/>
</div>

I want to remove and re-attach the SampleComponent2 based on some event from SampleComponent2.

Ad

Answer

Ad

You should let React handle component1 and 2 based on props you give it.

For example, with ES6 and a React 0.14 pure component:

const App = ({has2}) => 
  <div>
     <Component1 />
     {has2 && <Component2 />}
  </div>

If has2 is truthy, it will show Component2. Simply call render again whenever has2 changes and React does the rest.

Ad
source: stackoverflow.com
Ad