Skip to content

Instantly share code, notes, and snippets.

@alonbardavid
Created October 2, 2019 12:24
Show Gist options
  • Save alonbardavid/6ab23b58df1f483deb1cabe2b450dd10 to your computer and use it in GitHub Desktop.
Save alonbardavid/6ab23b58df1f483deb1cabe2b450dd10 to your computer and use it in GitHub Desktop.
Patterns-for-deriving-state gist1
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