Created
July 25, 2017 19:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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