Created
October 2, 2019 12:24
-
-
Save alonbardavid/6ab23b58df1f483deb1cabe2b450dd10 to your computer and use it in GitHub Desktop.
Patterns-for-deriving-state gist1
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
class SortedList extends React.Component { | |
onFilterChange = (event)=>{ | |
const filter = event.target.value; | |
const {sortKey} = this.state; | |
const filteredList = this.props.list.filter(item=>item.text.indexOf(filter)>=0) | |
this.setState({ | |
filter, | |
sortedList:sortByColumn(filteredList,sortKey) | |
}) | |
} | |
sortByKey = (column) =>{ | |
const sortedList = sortByColumn(this.state.list,column); | |
this.setState({ | |
sortedList, | |
sortKey:column | |
}) | |
} | |
render(){ | |
const {sortedList,filter} = this.state; | |
return <div> | |
{sortedList.map(item=> | |
<ItemView item={item} key={item.id} /> | |
)} | |
<button onClick={()=>this.sortByKey("columnA")}>Sort by A</button> | |
<button onClick={()=>this.sortByKey("columnB")}>Sort by B</button> | |
<input type="text" value={filter} | |
onChange={this.onFilterChange}>Sort by A</button> | |
</div> | |
} | |
} | |
function sortByColumn(list,column){ | |
return list.sort((a,b)=>a[column]>b[column]?1:a[column] < b[column]?-1:0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment