Skip to content

Instantly share code, notes, and snippets.

@knz21
Last active March 14, 2017 07:50
Show Gist options
  • Save knz21/68fc8a045c65e77c3f57b531789b5a49 to your computer and use it in GitHub Desktop.
Save knz21/68fc8a045c65e77c3f57b531789b5a49 to your computer and use it in GitHub Desktop.
React component of input tag receiving value and keeping cursor index.
var React = require('react');
module.exports = React.createClass({
propTypes: {
id: React.PropTypes.string.isRequired,
className: React.PropTypes.string,
value: React.PropTypes.string.isRequired,
placeholder: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
adjustCursor: React.PropTypes.func
},
getInitialState: function () {
return { index: 0 };
},
render: function () {
return (<input id={this.props.id} className={this.props.className} type="text" value={this.props.value}
placeholder={this.props.placeholder} onChange={this.props.onChange} autoComplete="off"/>);
},
componentDidUpdate: function (prevProps) {
if (!document.activeElement || document.activeElement.id !== this.props.id) {
return;
}
var input = document.getElementById(this.props.id);
input.value = this.props.value;
input.selectionStart = input.selectionEnd = this.getIndex(prevProps.value.length, this.props.value.length);
},
componentWillReceiveProps: function () {
this.setState({ index: document.getElementById(this.props.id).selectionStart });
},
getIndex: function (befValLen, aftValLen) {
if (this.props.adjustCursor) {
return this.props.adjustCursor(this.state.index, aftValLen - befValLen > 0);
}
return this.state.index;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment