Skip to content

Instantly share code, notes, and snippets.

Created July 24, 2017 16:13
Show Gist options
  • Save anonymous/5a2cc0f49e46a12431b77129211cf618 to your computer and use it in GitHub Desktop.
Save anonymous/5a2cc0f49e46a12431b77129211cf618 to your computer and use it in GitHub Desktop.
React Search
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
class Search extends React.Component {
constructor(props) {
super(props);
this.allItems = [{text: 'Hallo'}, {text:'Lola'}, {text:'Bu'}, {text:'bah'}, {text:'beh'}]
this.state = { filteredItems: this.allItems };
this.filterItems = this.filterItems.bind(this);
}
filterItems(e) {
let queryText = e.target.value
if (queryText === '') {
this.setState({filteredItems: this.allItems});
} else {
this.setState({filteredItems: this.allItems.filter(item => item.text.startsWith(queryText))});
}
}
render() {
return (
<div>
<h3> Search </h3>
<input onChange={this.filterItems}/>
<ResultList items={this.state.filteredItems}/>
</div>
)
}
}
class ResultList extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<ul>
{ this.props.items.map(item => (<li> { item.text } </li>)) }
</ul>
)
}
}
ReactDOM.render(
<Search />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment