I am struggling to use refs in React. They always return root DOM node of the component instead of reffed one.
Please consider the following example:
var AuthApp = React.createClass({
onSubmitClick: function(event) {
var usernameInput = this.getDOMNode(this.refs.username);
// This logs root <div> instead of <input>, why???
console.log(usernameInput);
},
render: function() {
return (
<div>
<input type="text" ref="username"/>
<input type="password" ref="password"/>
<input type="submit" onClick={this.onSubmitClick} />
</div>
);
}
});
I've inspected the code in excellent Chrome React addon, and it seems that this.refs.username
properly reflects <input>
tag:
Something wrong happens when I call this.getDOMNode
- it returns root <div>
specified in render()
instead of <input>
.
This code comes from React 0.12, but I've tried to do the same on 0.13 (I am aware of change to React.findDOMNode()
) and I get the same result.
What am I doing wrong?
When a component renders to a string, findDOMNode returns a text DOM node containing that value. As of React 16, a component may return a fragment with multiple children, in which case findDOMNode will return the DOM node corresponding to the first non-empty child.
In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all. When a component renders to null or false, findDOMNode returns null. When a component renders to a string, findDOMNode returns a text DOM node containing that value.
ReactDOM.render () does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children. ReactDOM.render () currently returns a reference to the root ReactComponent instance.
The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. The example below implements a common pattern: using the ref callback to store a reference to a DOM node in an instance property.
You should be using
var usernameInput = React.findDOMNode(this.refs.username);
to get a reference to the component's DOM node using refs
.
The getDOMNode
method has been deprecated
getDOMNode is deprecated and has been replaced with React.findDOMNode().
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