Last active
June 18, 2017 15:34
-
-
Save gianmarcotoso/73ec60724f0d85153e2d to your computer and use it in GitHub Desktop.
React Sort HoC
This file contains 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; | |
// byProperty supports dot notation for nested objects, like `person.city.name` | |
Sort.byPropertyWithComparator = (p, c) => (l, r) => c(p.split('.').reduce( (o,i) => o[i], l), p.split('.').reduce( (o,i) => o[i], r)); | |
Sort.asNumberWithComparator = (c) => (l, r) => c(parseFloat(l), parseFloat(r)); | |
Sort.asStringWithComparator = (c) => (l, r) => c(l.toString(), r.toString()); | |
export default Sort; |
Hey it would be cool if you could provide some example usage, greatly appreciated :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great!!!