Skip to content

Instantly share code, notes, and snippets.

@laserpants
Created July 25, 2015 13:25
Show Gist options
  • Save laserpants/1b4ae06a5f93e5165863 to your computer and use it in GitHub Desktop.
Save laserpants/1b4ae06a5f93e5165863 to your computer and use it in GitHub Desktop.
React: Set focus on input element
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')
);
@ibiBgOR
Copy link

ibiBgOR commented Oct 4, 2017

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.

@acontreras89
Copy link

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)
  }
  // ...

@jamesmcintyre
Copy link

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