Last active
March 14, 2017 07:50
-
-
Save knz21/68fc8a045c65e77c3f57b531789b5a49 to your computer and use it in GitHub Desktop.
React component of input tag receiving value and keeping cursor index.
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
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