Created
April 27, 2019 03:35
-
-
Save stephepush/a8afc4ed93c4fc14179c9efff520e52d to your computer and use it in GitHub Desktop.
Code as copied from Taming the State in React's Searchable List component from ~page 5
This file contains hidden or 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
| import React from 'react'; | |
| import List from "./List"; | |
| import Search from "./Search"; | |
| class SearchableList extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| this.state = { | |
| query: '', | |
| archivedItems: [] | |
| }; | |
| this.onChange = this.onChange.bind(this); | |
| this.onArchive = this.onArchive.bind(this); | |
| } | |
| onChange(event) { | |
| const { value } = event.target; | |
| this.setState({ | |
| query: value | |
| }); | |
| } | |
| onArchive(id){ | |
| const { archivedItems } = this.state; | |
| this.setState({ | |
| archivedItems: [...archivedItems, id] | |
| }); | |
| } | |
| render(){ | |
| const { list } = this.props; | |
| const { query, archivedItems } = this.state; | |
| const filteredList = list | |
| .filter(byQuery(query)) | |
| .filter(byArchived(archivedItems)); | |
| return ( | |
| <div> | |
| <Search query={query} onChange={this.onChange}> | |
| Search List: | |
| </Search> | |
| <List | |
| list={filteredList} | |
| onArchive={this.onArchive} | |
| /> | |
| </div> | |
| ); | |
| } | |
| } | |
| function byQuery(query){ | |
| return function(item) { | |
| return !query || | |
| item.name.toLowerCase().includes(query.toLowerCase()); | |
| } | |
| } | |
| function byArchived(archivedItems) { | |
| return function(item) { | |
| return !archivedItems.includes(item.id); | |
| } | |
| } | |
| export default SearchableList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment