Remove a Mounted React Component with React.unmountComponentAtNode()

While going through the codebase of React Bootstrap (for some reason), I came across an interesting implementation of a “React playground”. The code behind the playground is in ReactPlayground.js. I found this piece of interesting code there:

executeCode() {
  let mountNode = React.findDOMNode(this.refs.mount);

  try {
    React.unmountComponentAtNode(mountNode);
  } catch (e) {
    console.error(e);
  }

  // ... more code
}

So on changing the code (in the documentation), React.unmountComponentAtNode(mountNode); removes the live preview and then later in the same method (executeCode()), it as added again. So basically, due to this code, let’s discuss the React.unmountComponentAtNode() method quickly.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

It’s fairly straightforward, if you did a React.render(<Component />, container) to mount the Component in the container, then in order to reverse that, i.e., unmount that Component from the container (remove from DOM) and clean up all the attached event listeners/handlers and state, you can simple call React.unmountComponentAtNode(container) and it’ll do the job. On unmounting, the method will return true else false if there was nothing to unmount.

Keep in mind that you cannot call this on random parent containers to remove the DOM nodes they contain. It only sort of does the reverse of a React.render(). What I basically mean is, this won’t make any sense:

class Button extends React.Component {
  constructor() {
    super();

    this._handleClick = this._handleClick.bind(this);
  }

  _handleClick() {
    let mountNode = React.findDOMNode(this.refs.wassup);
    let unmount = React.unmountComponentAtNode(mountNode);
    // console.log(unmount); // false
  }

  render() {
    return (
      <div ref="wassup">
        <a href="#" onClick={this._handleClick}>Hello world!</a>
      </div>
    );
  }
}

React.render(<Button />, document.querySelector('#container'));

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

One thought on “Remove a Mounted React Component with React.unmountComponentAtNode()”

Leave a Reply

Your email address will not be published. Required fields are marked *