eriklharper eriklharper - 1 month ago 12
React JSX Question

React 0.13 this.getDOMNode() equivalent to React.findDOMNode()

This works perfectly fine in React version 0.12:

componentDidMount: function () {
var dom = this.getDOMNode();
}


The variable
dom
gets the actual DOM node for the rendered component. However, converting this to React 0.13 does not work as expected:

componentDidMount: function () {
var dom = React.findDOMNode();
// dom is undefined
}


I tried
React.findDOMNode(this)
which does not work either. Basically I'm just trying to fetch the top-level dom node rendered by the render function without using a ref. Is this possible?

Answer

Passing this as the parameter should definitely work:

React.findDOMNode(this);

If not, something else may be going on. See demo below:

var Test = React.createClass({
  componentDidMount: function() {
    var dom = React.findDOMNode(this);
    console.log(dom);
    alert(dom);
  },
  render: function() {
    return React.DOM.div(null, 'test');
  }
});

React.render(React.createElement(Test), document.getElementById('r'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react.js"></script>
<div id="r"></div>