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?
findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated in StrictMode .
getDOMNode() => DOMComponent. Returns the outer most DOMComponent of the current wrapper. Notes: can only be called on a wrapper of a single node.
In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.
Update React v0.14+
In React v0.14+ this has changed, you should now use the react-dom
module:
import ReactDOM from 'react-dom'; ReactDOM.findDOMNode(this);
ES6
class Test extends React.Component { componentDidMount() { const element = ReactDOM.findDOMNode(this); console.log(element); alert(element); } render() { return ( <div>test</div> ); } } ReactDOM.render(<Test />, document.getElementById('r'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="r" />
ES5
var Test = React.createClass({ componentDidMount: function() { var dom = ReactDOM.findDOMNode(this); console.log(dom); alert(dom); }, render: function() { return React.createElement('div', null, 'test'); } }); ReactDOM.render(React.createElement(Test), document.getElementById('r'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="r" />
React v0.13 and below
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With