Skip to content

Instantly share code, notes, and snippets.

@shiftkey
Created July 25, 2017 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiftkey/a713712182288b0870952fd5a1bfcebe to your computer and use it in GitHub Desktop.
Save shiftkey/a713712182288b0870952fd5a1bfcebe to your computer and use it in GitHub Desktop.
[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