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:
react-bootstrap.Input
class. 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.
in render
<FormControl
type='text'
ref={(c)=>this.formControlRef=c}
/>
in event handler
someHandler() {
ReactDOM.findDOMNode(this.formControlRef).focus();
}
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