Skip to content

Commit f7d4721

Browse files
committed
Added Table natural sort example to the docs
1 parent 0f7bdc0 commit f7d4721

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

docs/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,4 @@ Documentation
2626
* [Displaying items in reverse order](reverseList.md)
2727
* [Using AutoSizer](usingAutoSizer.md)
2828
* [Creating an infinite-loading list](creatingAnInfiniteLoadingList.md)
29-
* [Displaying a reverse list](reverseList.md)
29+
* [Natural sort Table](tableWithNaturalSort.md)

docs/tableWithNaturalSort.md

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
By default, `Table` assumes the sortable rows can be sorted in ascending or descending order.
2+
Clicking a column header the first time will trigger the `sort` callback with a suggested ordering of _ascending_.
3+
Clicking it a second time will call `sort` with a suggested ordering of _descending_.
4+
Clicking a third time will suggest _ascending_.
5+
6+
This is often desirable but it has a subtle side effect:
7+
Once you have sorted a `Table` there is no way to return to an unsorted, "natural" order.
8+
9+
Fortunately `Table` makes it easy for you to implement this functionality within your application code like so:
10+
11+
```jsx
12+
export default class NaturalSortTable extends Component {
13+
constructor (props, context) {
14+
super(props, context)
15+
16+
this.state = {
17+
list: props.list // Naturally sorted list
18+
}
19+
}
20+
21+
componentWillUpdate (nextProps, nextState) {
22+
const {
23+
sortBy: prevSortBy,
24+
sortDirection: prevSortDirection
25+
} = this.state
26+
27+
if (
28+
nextState.sortBy !== prevSortBy ||
29+
nextState.sortDirection !== prevSortDirection
30+
) {
31+
const { sortBy, sortDirection } = nextState
32+
33+
let { list } = this.props
34+
35+
if (sortBy) {
36+
list = list.sortBy(item => item[sortBy])
37+
if (sortDirection === SortDirection.DESC) {
38+
list = list.reverse()
39+
}
40+
}
41+
}
42+
}
43+
44+
render () {
45+
const { list, sortBy, sortDirection } = this.state
46+
47+
return (
48+
<Table
49+
{...this.props}
50+
sort={this._sort}
51+
sortBy={sortBy}
52+
sortDirection={sortDirection}
53+
>
54+
{/* <Column>s go here */}
55+
</Table>
56+
)
57+
}
58+
59+
_sort ({ sortBy, sortDirection }) {
60+
const {
61+
sortBy: prevSortBy,
62+
sortDirection: prevSortDirection
63+
} = this.state
64+
65+
// If list was sorted DESC by this column.
66+
// Rather than switch to ASC, return to "natural" order.
67+
if (prevSortDirection === SortDirection.DESC) {
68+
sortBy = null
69+
sortDirection = null
70+
}
71+
72+
this.setState({ sortBy, sortDirection })
73+
}
74+
}
75+
```

0 commit comments

Comments
 (0)