React autoFocus sets cursor to beginning of input value

Viewed 19719

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/

6 Answers

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.

This way the text of the input will be selected, ready to edit

<input
  type="text"
  defaultValue="Untitled"
  autoFocus
  onFocus={e => e.currentTarget.select()}
/>

In TypeScript:

private inputDOM: HTMLInputElement | null;

public componentDidMount() {
    if (this.inputDOM != null) {
        this.inputDOM.value = '';
        this.inputDOM.value = this.state.newRegionName;
    }
}

public render() {
    return <input ref={(ref: HTMLInputElement | null) => this.inputDOM = ref} type="text" autoFocus={true} value={this.state.inputValue} />;
}
Related