54

I'm trying to unmount a React.js node with this._rootNodeID

 handleClick: function() {

        React.unmountComponentAtNode(this._rootNodeID)

 }

But it returns false.

The handleClick is fired when I click on an element, and should unmount the root-node. Documentation on unmountComponentAtNode here

I've tried this as well:

React.unmountComponentAtNode($('*[data-reactid="'+this._rootNodeID+'"]')[0])

That selector works with jQuery.hide(), but not with unmounting it, while the documentation states it should be a DOMElement, like you would use for React.renderComponent

After a few more tests it turns out it works on some elements/selectors.

It somehow works with the selector: document.getElementById('maindiv'), where maindiv is an element not generated with React.js, and just plain html. Then it returns true.

But as soon as I try and select a different ElementById that is generated with React.js it returns false. And it wont work with document.body either, though they all essentially return the same thing if I console.log them (getElementsByClassName('bla')[0] also doesn't work)

There should be a simple way to select the node via this, without having to resort to jQuery or other selectors, I know it's in there somewhere..

1

6 Answers 6

98

Unmount components from the same DOM element that you mount them in. So if you did something like:

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

Then you would unmount it with:

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

Here is a simple JSFiddle where we mount the component and then unmount it after 3 seconds.

10
  • 4
    @TrySpace If you want to trigger the unmount from within the component itself, you could just pass the DOM element in as a prop and reference it when needed: http://jsfiddle.net/iamlacroix/JRy7W/2 Commented Feb 9, 2014 at 22:37
  • @TrySpace In your JSFiddle above, it didn't work because you were trying to call unmount on the rendered component #element & not its container you used to mount it #container. React doesn't replace the container itself, just its innerHTML. This way you can always reference that container again (e.g. for re-mounting with new props, replacing with a different component, etc.) Commented Feb 9, 2014 at 22:41
  • @MichaelLaCroix what if you have list of components inside a container and would only like to remove one? Since there's only one container, calling React.unmountComponentAtNode on that container will remove all components. How do you get around with it?
    – Marconi
    Commented Feb 20, 2014 at 16:22
  • 1
    @Marconi A top-level React component can only have one root node, so you would want to use logic based on the props or state of that component to determine whether or not a child component should be included. Commented Feb 20, 2014 at 21:16
  • @MichaelLaCroix hey thanks, but I managed last night by adding separate container for each sub component, then removing becomes easier since it has its own container.
    – Marconi
    Commented Feb 21, 2014 at 3:31
37

This worked for me. You may want to take extra precautions if findDOMNode returns null.

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
2
  • 1
    This code raises an exception if Component.render returns null (Component.getDOMNode() also returns null in this case).
    – JuliaCesar
    Commented Nov 17, 2014 at 14:29
  • 1
    This code works perfectly for me. Having adding parentNode helps me remove entire React component.
    – Henry Le
    Commented Jul 9, 2015 at 11:02
6

The example I use:

unmount: function() {
  var node = this.getDOMNode();
  React.unmountComponentAtNode(node);
  $(node).remove();
},

handleClick: function() {
  this.unmount();
}
1
  • 2
    Is the $(node) using jQuery? Commented Mar 22, 2016 at 17:55
2

You don't need to unmount the component the simple solution it's change the state and render a empty div

const AlertMessages = React.createClass({
  getInitialState() {
    return {
      alertVisible: true
    };
  },
  handleAlertDismiss() {
    this.setState({alertVisible: false});
  },
  render() {
    if (this.state.alertVisible) {
      return (
        <Alert bsStyle="danger" onDismiss={this.handleAlertDismiss}>
          <h4>Oh snap! You got an error!</h4>
        </Alert>
      );
    }
    return <div></div>
  }
});
1
  • Render an empty div saved my day. Thanks for the tip.
    – Triguna
    Commented Nov 24, 2021 at 12:08
1

As mentioned in the GitHub issue you filed, if you want access to a component's DOM node, you can use this.getDOMNode(). However a component can not unmount itself. See Michael's answer for the correct way to do it.

2
  • 2
    a component can not unmount itself that might be it
    – TrySpace
    Commented Feb 9, 2014 at 22:06
  • 2
    With react 0.14.x, this.getDOMNode has been deprecated. Please use ReactDOM.findDOMNode(this.refs.[nodeName]) for custom components or this.refs[nodeName] for supported JSX tags. Commented Jan 13, 2016 at 0:37
0

First , i am new to reactjs ,too . Of course we can control the Component all by switch the state , but as I try and test , i get that , the React.unmountComponentAtNode(parentNode) can only unmount the component which is rendered by React.render(<SubComponent>,parentNode). So <SubComponent> to be removed must be appened by React.render() method , so I write the code

<script type="text/jsx">

    var SubComponent = React.createClass({
        render:function(){
            return (
                    <div><h1>SubComponent to be unmouned</h1></div>
            );
        },
        componentWillMount:function(){
            console.log("componentWillMount");
        },
        componentDidMount:function(){
            console.log("componentDidMount");
        },
        componentWillUnmount:function(){
            console.log("componentWillUnmount");
        }

    });

    var App = React.createClass({

        unmountSubComponent:function(){
            var node = React.findDOMNode(this.subCom);
            var container = node.parentNode;
            React.unmountComponentAtNode(container);
            container.parentNode.removeChild(container)
        },

        componentDidMount:function(){
            var el = React.findDOMNode(this)
            var container = el.querySelector('.container');
            this.subCom = React.render(<SubComponent/> ,  container);
        },

        render:function(){

            return (
                <div className="app">
                    <div className="container"></div>
                    <button onClick={this.unmountSubComponent}>Unmount</button>
                </div>
            )
        }
    });

    React.render(<App/> , document.body);
</script>

Run the sample code in jsFiddle , and have a try .

Note: in the sample code React.findDOMNode is replaced by getDOMNode as the reactjs version problem .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.