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/
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With