Skip to content

Instantly share code, notes, and snippets.

@LucaColonnello
Forked from gianmarcotoso/Sort.jsx
Created March 9, 2016 21:30
Show Gist options
  • Save LucaColonnello/604c4091b994508d1982 to your computer and use it in GitHub Desktop.
Save LucaColonnello/604c4091b994508d1982 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;
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