Created
July 25, 2015 13:25
-
-
Save laserpants/1b4ae06a5f93e5165863 to your computer and use it in GitHub Desktop.
React: Set focus on input element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Hello = React.createClass({ | |
getInitialState: function() { | |
return { | |
value: 1, | |
editMode: false | |
}; | |
}, | |
edit: function() { | |
this.setState({editMode: true}); | |
}, | |
handleChange: function(event) { | |
this.setState({value: event.target.value}); | |
}, | |
focusInput(component) { | |
if (component) { | |
React.findDOMNode(component).focus(); | |
} | |
}, | |
render: function() { | |
if (true === this.state.editMode) { | |
return ( | |
<input | |
ref={this.focusInput} | |
type="text" | |
value={this.state.value} | |
onChange={this.handleChange} /> | |
); | |
} | |
return ( | |
<div>The value is: <span>{this.state.value}</span> | |
<button onClick={this.edit}> | |
Edit | |
</button> | |
</div> | |
); | |
} | |
}); | |
React.render( | |
<Hello name="World" />, | |
document.getElementById('container') | |
); |
I had the same problem as @ibiBgOR and ended up with something like this:
// ...
componentDidMount() {
if (!this.input) return
this.input.focus()
this.input.setSelectionRange(this.input.value.length, this.input.value.length)
}
// ...
Had a weird issue where the input having "display: none" (before re-render with new style) meant the focus couldn't apply to it so a quick and dirty solution (gives time for render with new style):
setTimeout(() => {
this.input.focus()
this.input.setSelectionRange(this.input.value.length, this.input.value.length)
}, 20);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes this does focus the input element. But sadly it does not jump right to the end of the existing text. I don't know an solution for this but maybe another one could take a look at this.