Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on a react-bootstrap.Input field using refs.x.getDOMNode.focus

The JSX:

var Button = require("react-bootstrap").Button;
var Input = require("react-bootstrap").Input;
var MyClass = React.createClass({
        onclick: function () {
           this.refs.email.getDOMNode().focus();
           console.log('DOM element', this.refs.email.getDOMNode());
        }
        render: function () {
          return (
             <div>
                <Button onClick={this.onlick}>Login</Button>
                <Input ref='email' type='email' />
             </div>
            );
        },
    });  

Notes:

  1. The input field is a react-bootstrap.Input class.
  2. The getDOMNode().focus() concept is from Facebook react docs

When the button onclick handler runs, the email input field should be getting the focus, but it's not happening. I found that the react-bootstrap Input field class is rendering the real DOM input field inside a wrapping div. This is the output of the console.log:

<div class="form-group" data-reactid=".1awy8d4e9kw.1.3.$=1$3:0.0.0.1.0">
  <input class="form-control" type="email" data-reactid=".1awy8d4e9kw.1.3.$=1$3:0.0.0.1.0.1:$input">
</div>

So looks like the input isn't getting the focus because the focus is applied on the wrapping div, which rejects it (I use document.activeElement in the console to check).

Question is, how to focus on the real input element?

Note: A bit unrelated but React respects the autoFocus property. That's useful in case the focus is needed to be set immediately after rendering. Still, it's not a substitute for the programmatic way.

like image 612
tivoni Avatar asked Jan 02 '15 06:01

tivoni


1 Answers

in render

<FormControl
  type='text'
  ref={(c)=>this.formControlRef=c}
  />

in event handler

someHandler() {
  ReactDOM.findDOMNode(this.formControlRef).focus();
}
like image 71
ChetPrickles Avatar answered Oct 27 '22 23:10

ChetPrickles