Skip to content

Instantly share code, notes, and snippets.

@gianmarcotoso
Last active June 18, 2017 15:34
Show Gist options
  • Save gianmarcotoso/73ec60724f0d85153e2d to your computer and use it in GitHub Desktop.
Save gianmarcotoso/73ec60724f0d85153e2d to your computer and use it in GitHub Desktop.
React Sort HoC
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;
@LucaColonnello
Copy link

Great!!!

@azz0r
Copy link

azz0r commented Jun 18, 2017

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