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