UNPKG

2.18 kBJavaScriptView Raw
1import React, {Component} from 'react';
2import {render} from 'react-dom';
3import {Table, Column} from 'react-virtualized';
4import {sortableContainer, sortableElement} from 'react-sortable-hoc';
5import arrayMove from 'array-move';
6import 'react-virtualized/styles.css';
7
8const ROW_HEIGHT = 30;
9const HEADER_ROW_HEIGHT = 20;
10const COL_WIDTH = 100;
11
12const SortableHeader = sortableElement(({children, ...props}) =>
13 React.cloneElement(children, props),
14);
15
16const SortableHeaderRowRenderer = sortableContainer(
17 ({className, columns, style}) => (
18 <div className={className} role="row" style={style}>
19 {React.Children.map(columns, (column, index) => (
20 <SortableHeader index={index}>{column}</SortableHeader>
21 ))}
22 </div>
23 ),
24);
25
26class TableWithSortableColumns extends Component {
27 state = {
28 cols: [
29 {dataKey: 'col1', label: 'Column 1'},
30 {dataKey: 'col2', label: 'Column 2'},
31 {dataKey: 'col3', label: 'Column 3'},
32 ],
33 rows: [
34 {col1: 'row1 col1', col2: 'row1 col2', col3: 'row1 col3'},
35 {col1: 'row2 col1', col2: 'row2 col2', col3: 'row2 col3'},
36 {col1: 'row3 col1', col2: 'row3 col2', col3: 'row3 col3'},
37 ],
38 };
39
40 onSortEnd = ({oldIndex, newIndex}) => {
41 this.setState(({cols}) => ({
42 cols: arrayMove(cols, oldIndex, newIndex),
43 }));
44 };
45
46 getRow = ({index}) => {
47 const {rows} = this.state;
48 return rows[index];
49 };
50
51 renderHeaderRow = (params) => {
52 return (
53 <SortableHeaderRowRenderer
54 {...params}
55 axis="x"
56 lockAxis="x"
57 onSortEnd={this.onSortEnd}
58 />
59 );
60 };
61
62 render() {
63 const {rows, cols} = this.state;
64
65 return (
66 <Table
67 width={COL_WIDTH * rows.length}
68 height={HEADER_ROW_HEIGHT + ROW_HEIGHT * rows.length}
69 headerHeight={ROW_HEIGHT}
70 rowHeight={ROW_HEIGHT}
71 rowCount={rows.length}
72 rowGetter={this.getRow}
73 headerRowRenderer={this.renderHeaderRow}
74 >
75 {cols.map((col) => (
76 <Column {...col} key={col.dataKey} width={COL_WIDTH} />
77 ))}
78 </Table>
79 );
80 }
81}
82
83render(<TableWithSortableColumns />, document.getElementById('root'));
84
\No newline at end of file