-
-
Save LucaColonnello/604c4091b994508d1982 to your computer and use it in GitHub Desktop.
React Sort HoC
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 { Component } from 'react'; | |
let Sort = Sortable => class extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
items: [] | |
} | |
} | |
componentWillReceiveProps(nextProps) { | |
this.updateSort(nextProps); | |
} | |
componentDidMount() { | |
this.updateSort(this.props); | |
} | |
updateSort({items, reverse, comparator}) { | |
let _items = [...items]; | |
_items.sort(comparator); | |
if (reverse) | |
_items.reverse(); | |
this.setState({items: _items}); | |
} | |
render() { | |
return ( | |
<Sortable {...this.props} items={this.state.items} /> | |
); | |
} | |
} | |
Sort.propTypes = { | |
items: React.PropTypes.array.isRequired, | |
reverse: React.PropTypes.bool, | |
comparator: React.PropTypes.func | |
} | |
Sort.defaultProps = { | |
reverse: false, | |
comparator: Sort.lessThan | |
} | |
Sort.lessThan = (l, r) => r < l; | |
Sort.lessThanOrEqual = (l, r) => r <= l; | |
Sort.greaterThan = (l, r) => r > l; | |
Sort.greaterThanOrEqual = (l, r) => r >= l; | |
Sort.byPropertyWithComparator = (p, c) => (l, r) => c(l[p], r[p]); | |
Sort.asNumberWithComparator = (c) => (l, r) => c(parseFloat(l), parseFloat(r)); | |
Sort.asStringWithComparator = (c) => (l, r) => c(l.toString(), r.toString()); | |
export default Sort; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment