NqdGNx ('-' * 6)
A Pen by Captain Anonymous on CodePen.
| <div id="Search"></div> |
NqdGNx ('-' * 6)
A Pen by Captain Anonymous on CodePen.
| /** @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; | |
| } |
Here is the codepen for demo. As you can see
componentWillMountshows all the items initially in this case since the items are in the client side but we can avoid showing them and makedebouncedajaxcalls onkeyupwhen the user types.