React getDOMNode always returns the root of the DOM node component instead of deferred

I am trying to use refs in React. They always return the root DOM node of the component instead of the deferred 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 checked the code in the excellent Chrome React addon and it seems that this.refs.username correctly reflects the <input> :

screenshot of React / Chrome inspector

Something goes wrong when I call this.getDOMNode - it returns the root <div> specified in render() instead of <input> .

This code comes from React 0.12, but I tried to do the same at 0.13 (I know of a change to React.findDOMNode() ), and I get the same result.

What am I doing wrong?

+6
source share
3 answers

You should use this.refs['username'].getDOMNode() . But perhaps in newer versions of React it is better to use React.findDOMNode , as advised by adeneo.

+3
source

You have to use

 var usernameInput = React.findDOMNode(this.refs.username); 

to get a reference to the DOM node component using refs .

getDOMNode method deprecated

getDOMNode is deprecated and has been replaced with React.findDOMNode ().

+5
source

To extend adeneo's answer, instead of executing React.findDOMNode(this.refs.username) you can simply do this.refs.username because the ref that is returned is , DOM Node.

See the link for reference: https://facebook.imtqy.com/react/blog/2015/10/07/react-v0.14.html#dom-node-refs

0
source

Source: https://habr.com/ru/post/986047/


All Articles