Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 520
ReganPerkins Avatar asked Mar 11 '16 23:03

ReganPerkins


2 Answers

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

like image 133
Ted A. Avatar answered Oct 07 '22 03:10

Ted A.


This actually works:

componentDidMount() {
    const input = this.input;
    const length = input.value.length;
    input.focus();
    input.setSelectionRange(length, length);
}

render() {
   return (
       <input ref={ref => this.input = ref} ... >
   )
}

PS. If you need to support IE8 and below you'll need to use IE-specific checks.

like image 31
Spadar Shut Avatar answered Oct 07 '22 03:10

Spadar Shut