Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[react] a workaround for the caret position being reset after updating the value
// source: @aliaksandr-master at https://github.com/facebook/react/issues/955#issuecomment-316118969
// documenting it here in case it gets edited or disappeared from the issue
const FieldInput = class FieldInput extends Component {
static propTypes = {
onChange: PropTypes.func,
value: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ])
};
constructor (...args) {
super(...args);
this.handleChange = this.handleChange.bind(this);
this._rawStr = '';
this._caretPosition = 0;
}
componentDidUpdate ({ value }) {
if (this.props.value !== value) {
const str = this._rawStr.substr(0, this._caretPosition);
const index = String(this.props.value).indexOf(str) + this._caretPosition;
if (index !== -1) {
this.refs.input.selectionStart = this.refs.input.selectionEnd = index;
}
}
}
handleChange (ev) {
this._rawStr = String(ev.target.value);
this._caretPosition = Number(ev.target.selectionEnd);
if (this.props.onChange) {
this.props.onChange(ev);
}
}
render () {
return (<input {...this.props} ref="input" onChange={this.handleChange} />);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment