Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active August 29, 2015 14:11
Show Gist options
  • Save lovasoa/b02000701c0ac574c0af to your computer and use it in GitHub Desktop.
Save lovasoa/b02000701c0ac574c0af to your computer and use it in GitHub Desktop.
React auto-completion component
var AutoCompletionInput = React.createClass({
getInitialState: function() {
return {completion:'',prevText:''};
},
getCompletion : function(txt){
if (txt.length === 0|| this.state.prevText.length>=txt.length) return '';
var finder = function(x){return x.startsWith(txt)}.bind(this);
var repl = this.props.completionValues.find(finder);
if (!repl) return '';
else return repl.substring(txt.length);
},
componentDidUpdate: function () {
var input = this.getDOMNode(),
text = this.props.value,
comp = this.state.completion;
input.focus();
input.setSelectionRange(text.length-comp.length, text.length);
},
onChange: function(e) {
var txt = e.target.value;
var comp = this.getCompletion(txt);
this.setState({completion:comp,prevText:txt});
this.props.onChange(txt+comp);
},
render: function(){
var value = this.props.value;
return <input onChange={this.onChange} value={value} />;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment