Search code examples
javascriptreactjs

React autoFocus sets cursor to beginning of input value


I have a controlled input that has a value initially showing. I have set that input to autoFocus but the cursor appears at the beginning of the input when I am wanting it to appear at the end. I understand this might be because the autoFocus is added before the value is but I'm not 100% sure.

What would be the best way to accomplish the cursor initializing at the end of the input field?

var Test = React.createClass({

    getInitialState: function() {
        return {
           teamId: 'fdsfds'
        };
    },

    render: function() {
        return (
                <input type="text" autoFocus value={this.state.teamId} onChange={this.setTeamId} />
        );
    },

    setTeamId: function(event) {
        this.setState({ teamId: id });
    },

});

ReactDOM.render(
  <Test />,
  document.getElementById('container')
);

https://jsfiddle.net/69z2wepo/34486/


Solution

  • One solution:

    <input
      type="text"
      autoFocus
      value={this.state.teamId}
      onChange={this.setTeamId}
      onFocus={function(e) {
        var val = e.target.value;
        e.target.value = '';
        e.target.value = val;
      }}
    />
    

    https://jsfiddle.net/o3s05zz4/1/

    Adaptation of this answer: https://stackoverflow.com/a/2345915/1589521