Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React's getDOMNode always return component's root DOM node instead of reffed one

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:

screenshot of React/Chrome inspector

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?

like image 294
mspanc Avatar asked Apr 27 '15 11:04

mspanc


People also ask

What does finddomnode return in react 16?

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.

Can I use a ref instead of finddomnode?

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.

Does reactdom render modify the container node?

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.

How do I store a reference to a DOM node in react?

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.


1 Answers

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().

like image 186
adeneo Avatar answered Sep 18 '22 13:09

adeneo