Skip to content

Instantly share code, notes, and snippets.

@sathify
Created May 28, 2015 19:59
Show Gist options
  • Save sathify/32087dfd0e556cffad4c to your computer and use it in GitHub Desktop.
Save sathify/32087dfd0e556cffad4c to your computer and use it in GitHub Desktop.
NqdGNx
<div id="Search"></div>
/** @jsx React.DOM */
var AutoComplete = React.createClass({
getInitialState: function() {
return {
allItems: [
'Ronald',
'Bob',
'Derek',
'Anthony',
'Satheesh',
'Nicole',
'Taro',
'Perk',
'Ben',
'Zeus'
],
items: []
}
},
filterItems: function(event) {
var list = this.state.allItems;
list = list.filter(function(item) {
return item.toLowerCase().indexOf(
event.target.value.toLowerCase()) !== -1;
});
this.setState({
items: list
});
},
componentWillMount: function() {
this.setState({
items: this.state.allItems
})
},
render: function() {
return ( <div className="dropdown">
<input type="text"
onChange = {
this.filterItems
}
/> <Dropdown items = {
this.state.items
}
/> </div>
);
}
});
var Dropdown = React.createClass({
render: function() {
return ( <ul> {
this.props.items.map(function(item) {
return <li> {
item
} </li>
})
} </ul>
);
}
});
React.renderComponent( <AutoComplete /> , document.getElementById('Search'));
body {
background: grey;
margin: 20px;
}
.dropdown {
margin: auto;
width: 200px;
}
input {
border-radius: 3px;
}
@sathify
Copy link
Author

sathify commented May 28, 2015

Here is the codepen for demo. As you can see componentWillMount shows all the items initially in this case since the items are in the client side but we can avoid showing them and make debounced ajax calls on keyup when the user types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment