+Key constants, prop/callback changes, controllable filters and resizing, subRow + pivoting expansion

This commit is contained in:
Tanner Linsley
2017-05-09 13:12:18 -06:00
parent 307d37421e
commit c24cc37c7d
12 changed files with 359 additions and 158 deletions
+2
View File
@@ -29,6 +29,7 @@ import Filtering from '../stories/Filtering.js'
import ControlledTable from '../stories/ControlledTable.js'
import PivotingOptions from '../stories/PivotingOptions.js'
import EditableTable from '../stories/EditableTable.js'
import SubRows from '../stories/SubRows.js'
//
configure(() => {
storiesOf('1. Docs')
@@ -63,4 +64,5 @@ configure(() => {
.add('Custom Filtering', Filtering)
.add('Controlled Component', ControlledTable)
.add('Editable table', EditableTable)
.add('Sub Rows', SubRows)
}, module)
+16 -13
View File
@@ -1,27 +1,30 @@
## 6.0.0
- Updated/New Renderers:
- `Cell` - deprecates and replaces `render`
- `Header` - deprecates and replaces `header`
- `Footer` - deprecates and replaces `footer`
##### New Features
- New Renderers:
- `Aggregated` - Custom renderer for aggregated cells
- `Pivot` - Custom renderer for Pivoted Cells (utilizes `Expander` and `PivotValue`)
- `PivotValue` - Custom renderer for Pivot cell values
- `PivotValue` - Custom renderer for Pivot cell values (deprecates the undocumented `pivotRender` option)
- `Expander` - Custom renderer for Pivot cell Expander
- `Filter`- Custom renderer for Filters
- Pivot Columns are now visibly separate and sorted/filtered independently.
- Custom sorting methods per instance via `sortMethod` and per column via `column.sortMethod`
- Prevent transitions while column resizing for a smoother resize effect.
- You may now use `column.resizable` to restrict or allow resizing for specific columns
- Disable text selection while resizing columns.
- All callbacks can now be utilized without needing to hoist and manage the piece of state they export. That is what their prop counterparts are for, so now the corresponding prop is used instead of the callback to detect a "fully controlled" state.
- Callbacks now provide the destination state as the primary parameter(s). This makes hoisting and controlling the state in redux or component state much easier. eg.
- `onSorting` no longer requires you to build your own toggle logic
- `onResize` no longer requires you to build your own resize logic
- `onChange` callback is now deprecated in favor of the better labeled `onFetchData` prop, which will always fires when a new data model needs to be fetched (or is build internally).
- `onFilteringChange` has been renamed to `onFilterChange` for simplicity and consistency.
##### Breaking API Changes
* Removed `pivotRender` column option. You can now control how the value is displayed by overriding the `PivotValueComponent` or the individual column's `PivotValue` renderer.
See [Pivoting Options Story](https://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Pivoting%20Options&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel) for a reference on how to customize pivot column rendering.
- New Renderers:
- `Cell` - deprecates and replaces `render`
- `Header` - deprecates and replaces `header`
- `Footer` - deprecates and replaces `footer`
- `Filter`- deprecates and replaces `filterRender`
- Callbacks now provide the destination state as the primary parameter(s). This makes hoisting and controlling the state in redux or component state much easier. eg.
- `onSorting` no longer requires you to build your own toggle logic
- `onResize` no longer requires you to build your own resize logic
- The `onChange` callback is now deprecated in favor of the better labeled `onFetchData` prop, which will always fires when a new data model needs to be fetched (or if not using `manual`, when new data is materialized internally).
- The `filtering` prop has been renamed to `filters` for simplicity and consistency.
- The `onFilteringChange` callback has been renamed to `onFilterChange` for simplicity and consistency.
- `cellInfo.row` and `rowInfo.row` now reference the materialize data for the table. To reference the original row, use `cellInfo.original` and `rowInfo.original`
- Removed `pivotRender` column option. You can now control how the value is displayed by overriding the `PivotValueComponent` or the individual column's `PivotValue` renderer. See [Pivoting Options Story](https://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Pivoting%20Options&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel) for a reference on how to customize pivot column rendering.
+74 -31
View File
@@ -178,7 +178,7 @@ These are all of the available props (and their default values) for the main `<R
onPageChange: undefined,
onPageSizeChange: undefined,
onSortingChange: undefined,
onFilterChange: undefined,
onFiltersChange: undefined,
onResize: undefined,
onExpandRow: undefined,
@@ -300,31 +300,22 @@ Or just define them as props
```javascript
[{
// Renderers
// Provide a JSX element or stateless function to a Renderer to display whatever you want as the column's cell with access to the entire row
// cellInfo: {
// value: the accessed value of the column
// rowValues: an object of all of the accessed values for the row
// row: the original row of data supplied to the table
// column: the column properties (id, header, sortable, ...)
// index: the original index of the data supplied to the table
// viewIndex: the index of the row in the current page
// }
Cell: JSX | String | Function | cellInfo => <span>{value}</span>,
Header: JSX | String | Function | cellInfo => <div>Header Name</div>,
Footer: JSX | String | Function | cellInfo => <div>Footer Name</div>,
Filter: JSX | cellInfo => (
<select onChange={event => onFilterChange(event.target.value)} value={filter ? filter.value : ''}></select>
// The value passed to onFilterChange will be the value passed to filter.value of the filterMethod
// Renderers - For more information, see "Renderers" section below
Cell: JSX | String | Function // Used to render a standard cell, defaults to the accessed value
Header: JSX | String | Function // Used to render the header of a column or column group
Footer: JSX | String | Function // Used to render the footer of a column
Filter: JSX | cellInfo => ( // Used to render the filter UI of a filter-enabled column
<select onChange={event => onFiltersChange(event.target.value)} value={filter ? filter.value : ''}></select>
// The value passed to onFiltersChange will be the value passed to filter.value of the filterMethod
)
Aggregated: JSX | String | Function | cellInfo => <span>{values.join(',')}</span>,
Pivot: JSX | String | Function | cellInfo => (
Aggregated: JSX | String | Function // Used to render aggregated cells. Defaults to a comma separated list of values.
Pivot: JSX | String | Function | cellInfo => ( // Used to render a pivoted cell
<span>
<Expander/><PivotValue />
<Expander/><PivotValue /> // By default, will utilize the the PivotValue and Expander components at run time
</span>
),
PivotValue: JSX | String | Function | cellInfo => <div>{value}</div>,
Expander: JSX | String | Function | cellInfo => <MyColumnExpander />,
PivotValue: JSX | String | Function // Used to render the value inside of a Pivot cell
Expander: JSX | String | Function // Used to render the expander in both Pivot and Expander cells
// General
accessor: 'propertyName', // or Accessor eg. (row) => row.propertyName (see "Accessors" section for more details)
@@ -371,6 +362,51 @@ Or just define them as props
}]
```
## Renderers
React Table supports very flexible renderers for just about everything:
- `Cell` - Renders a standard cell
- `Header` - Renders a column header or column group header
- `Footer` - Renders a column footer
- `Filter` - Renders a column's filter UI
- `Aggregated` - Renders an aggregated cell
- `Pivot` - Renders a pivoted cell (by default, will utilize `Expander` and `PivotValue` renderers)
- `PivotValue` - Renders the value inside a `Pivot` renderer
- `Expander` - Renders the Expander used in both the default `Pivot` renderer and any expander-designated column
Any of these renderers can be one of the following:
- A React Class
- JSX or any rendered react component
- Stateless functional component
- Function that returns any primitive
All of these formats receive the following props:
```javascript
{
// Row-level props
row: Object, // the materialized row of data
original: , // the original row of data
index: '', // the index of the row in the original arra
viewIndex: '', // the index of the row relative to the current view
level: '', // the nesting level of this row
nestingPath: '', // the nesting path of this row
aggregated: '', // true if this row's values were aggregated
groupedByPivot: '', // true if this row was produced by a pivot
subRows: '', // any sub rows defined by the `subRowKey` prop
// Cells-level props
isExpanded: '', // true if this row is expanded
value: '', // the materialized value of this cell
resized: '', // the resize information for this cell's column
show: '', // true if the column is visible
width: '', // the resolved width of this cell
maxWidth: '', // the resolved maxWidth of this cell
tdProps: '', // the resolved tdProps from `getTdProps` for this cell
columnProps: '', // the resolved column props from 'getProps' for this cell's column
classes: '', // the resolved array of classes for this cell
styles: '' // the resolved styles for this cell
}
```
## Accessors
Accessors are functions that return the value to populate the row's value for the column.
This lets the render function not have to worry about accessing the correct data, the value is automatically populated in it's props.
@@ -416,7 +452,7 @@ const columns = [{
## Custom Cell, Header and Footer Rendering
You can use any react component or JSX to display content in column headers, cells and footers. Any component you use will be passed the following props (if available):
- `row` - Original row from your data
- `rowValues` - The post-accessed values from the original row
- `row` - The post-accessed values from the original row
- `index` - The index of the row
- `viewIndex` - the index of the row relative to the current page
- `level` - The nesting depth (zero-indexed)
@@ -657,29 +693,36 @@ Here are the props and their corresponding callbacks that control the state of t
// Props
page={0} // the index of the page you wish to display
pageSize={20} // the number of rows per page to be displayed
sorting={[{
sorting={[{ // the sorting model for the table
id: 'lastName',
desc: true
}, {
id: 'firstName',
desc: true
}]} // the sorting model for the table
expandedRows={{
}]}
expandedRows={{ // The nested row indexes on the current page that should appear expanded
1: true,
4: true,
5: {
2: true,
3: true
}
}} // The nested row indexes on the current page that should appear expanded
resizing={[...]} // the current resized column model
}}
filters={[{ // the current filters model
id: 'lastName',
value: 'linsley'
}]}
resizing={[{ // the current resized column model
"id": "lastName",
"value": 446.25
}]}
// Callbacks
onPageChange={(pageIndex) => {...}} // Called when the page index is changed by the user
onPageSizeChange={(pageSize, pageIndex) => {...}} // Called when the pageSize is changed by the user. The resolve page is also sent to maintain approximate position in the data
onSortingChange={(newSorting, column, shiftKey) => {...}} // Called when a sortable column header is clicked with the column itself and if the shiftkey was held. If the column is a pivoted column, `column` will be an array of columns
onExpandRow={(newExpandedRows, index, event) => {...}} // Called when an expander is clicked. Use this to manage `expandedRows`
onFilterChange={(column, value) => {...}} // Called when a user enters a value into a filter input field or the value passed to the onFilterChange handler by the filterRender option.
onFiltersChange={(column, value) => {...}} // Called when a user enters a value into a filter input field or the value passed to the onFiltersChange handler by the filterRender option.
onResize={(newResizing, event) => {...}} // Called when a user clicks on a resizing component (the right edge of a column header)
/>
```
@@ -736,7 +779,7 @@ By default the table tries to filter by checking if the row's value starts with
If you want to override a particular column's filtering method, you can set the `filterMethod` option on a column.
To completely override the filter that is shown, you can set the `filterRender` column option. Using this option you can specify the JSX that is shown. The option is passed an `onFilterChange` method which must be called with the the value that you wan't to pass to the `filterMethod` option whenever the filter has changed.
To completely override the filter that is shown, you can set the `filterRender` column option. Using this option you can specify the JSX that is shown. The option is passed an `onFiltersChange` method which must be called with the the value that you wan't to pass to the `filterMethod` option whenever the filter has changed.
See <a href="http://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Custom%20Filtering&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel" target="\_parent">Custom Filtering</a> demo for examples.
@@ -755,7 +798,7 @@ Object.assign(ReactTableDefaults, {
TdComponent: component,
TfootComponent: component,
ExpanderComponent: component,
AggregateComponent: component,
AggregatedComponent: component,
PivotValueComponent: component,
PivotComponent: component,
FilterComponent: component,
File diff suppressed because one or more lines are too long
+19 -12
View File
@@ -21,7 +21,7 @@ export default {
freezeWhenExpanded: false,
defaultSorting: [],
showFilters: false,
defaultFiltering: [],
defaultFilters: [],
defaultFilterMethod: (filter, row, column) => {
const id = filter.pivotId || filter.id
return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true
@@ -33,25 +33,30 @@ export default {
// page: undefined,
// pageSize: undefined,
// sorting: undefined,
// expandedRows: {},
// resizing: [],
// expandedRows: {},
// Controlled State Callbacks
onExpandSubComponent: undefined,
onPageChange: undefined,
onPageSizeChange: undefined,
onSortingChange: undefined,
onFilterChange: undefined,
onFiltersChange: undefined,
onResize: undefined,
onExpandRow: undefined,
// Pivoting
pivotBy: undefined,
// Key Costansts
pivotValKey: '_pivotVal',
pivotIDKey: '_pivotID',
subRowsKey: '_subRows',
// Pivoting State Callbacks
onExpandRow: undefined,
aggregatedKey: '_aggregated',
nestingLevelKey: '_nestingLevel',
originalKey: '_original',
indexKey: '_index',
groupedByPivotKey: '_groupedByPivot',
// Server-side Callbacks
onFetchData: () => null,
@@ -165,13 +170,13 @@ export default {
},
TdComponent: _.makeTemplateComponent('rt-td'),
TfootComponent: _.makeTemplateComponent('rt-tfoot'),
FilterComponent: ({filter, onFilterChange}) => (
FilterComponent: ({filter, onChange}) => (
<input type='text'
style={{
width: '100%'
}}
value={filter ? filter.value : ''}
onChange={(event) => onFilterChange(event.target.value)}
onChange={(event) => onChange(event.target.value)}
/>
),
ExpanderComponent: ({isExpanded}) => (
@@ -182,10 +187,12 @@ export default {
PivotValueComponent: ({subRows, value}) => (
<span>{value} {subRows && `(${subRows.length})`}</span>
),
AggregateComponent: ({subRows, column}) => {
const previewValues = subRows.map((row, i) => (
<span key={i}>{row[column.id]}{i < subRows.length - 1 ? ', ' : ''}</span>
))
AggregatedComponent: ({subRows, column}) => {
const previewValues = subRows
.filter(d => typeof d[column.id] !== 'undefined')
.map((row, i) => (
<span key={i}>{row[column.id]}{i < subRows.length - 1 ? ', ' : ''}</span>
))
return (
<span>{previewValues}</span>
)
+59 -53
View File
@@ -36,7 +36,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
pageSize: props.defaultPageSize || 10,
sorting: props.defaultSorting,
expandedRows: {},
filtering: props.defaultFiltering,
filters: props.defaultFilters,
resizing: props.defaultResizing,
currentlyResizing: false,
skipNextSort: false
@@ -77,19 +77,24 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
noDataText,
showFilters,
resizable,
// Property keyspivotValKey,
pivotIDKey,
pivotValKey,
pivotBy,
subRowsKey,
aggregatedKey,
originalKey,
indexKey,
groupedByPivotKey,
// State
loading,
pageSize,
page,
sorting,
filtering,
filters,
resizing,
pages,
// Pivoting State
pivotValKey,
pivotIDKey,
pivotBy,
subRowsKey,
expandedRows,
onExpandRow,
// Components
@@ -109,7 +114,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
ExpanderComponent,
PivotValueComponent,
PivotComponent,
AggregateComponent,
AggregatedComponent,
FilterComponent,
// Data model
resolvedData,
@@ -388,7 +393,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
...columnHeaderProps.rest
}
const filter = filtering.find(filter => filter.id === column.id)
const filter = filters.find(filter => filter.id === column.id)
const ResolvedFilterComponent = column.Filter || FilterComponent
@@ -411,7 +416,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
{
column,
filter,
onFilterChange: (value) => (this.filterColumn(column, value))
onChange: (value) => (this.filterColumn(column, value))
},
defaultProps.column.Filter
)
@@ -422,13 +427,14 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
const makePageRow = (row, i, path = []) => {
const rowInfo = {
row: row.__original,
rowValues: row,
index: row.__index,
original: row[originalKey],
row: row,
index: row[indexKey],
viewIndex: ++rowIndex,
level: path.length,
nestingPath: path.concat([i]),
aggregated: !!row[subRowsKey],
aggregated: row[aggregatedKey],
groupedByPivot: row[groupedByPivotKey],
subRows: row[subRowsKey]
}
const isExpanded = _.get(expandedRows, rowInfo.nestingPath)
@@ -448,11 +454,6 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
{...trProps.rest}
>
{allVisibleColumns.map((column, i2) => {
const cellInfo = {
...rowInfo,
isExpanded,
column: {...column}
}
const resized = resizing.find(x => x.id === column.id) || {}
const show = typeof column.show === 'function' ? column.show() : column.show
const width = _.getFirstDefined(resized.value, column.width, column.minWidth)
@@ -460,8 +461,6 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
const tdProps = _.splitProps(getTdProps(finalState, rowInfo, column, this))
const columnProps = _.splitProps(column.getProps(finalState, rowInfo, column, this))
const value = cellInfo.rowValues[column.id]
const classes = [
tdProps.className,
column.className,
@@ -474,6 +473,27 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
...columnProps.style
}
const cellInfo = {
...rowInfo,
isExpanded,
column: {...column},
value: rowInfo.row[column.id],
resized,
show,
width,
maxWidth,
tdProps,
columnProps,
classes,
styles
}
const value = cellInfo.value
let interactionProps
let isBranch
let isPreview
const onExpanderClick = (e) => {
let newExpandedRows = _.clone(expandedRows)
if (isExpanded) {
@@ -494,35 +514,24 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
}
// Default to a standard cell
let resolvedCell = _.normalizeComponent(column.Cell, {
...cellInfo,
value
}, value)
let resolvedCell = _.normalizeComponent(column.Cell, cellInfo, value)
let interactionProps
let isBranch
let isPreview
let expandable
// Resolve Aggregate Renderer
const ResolvedAggregateComponent = column.Aggregated ||
!column.aggregate && AggregateComponent
// Resolve ExpanderComponent
// Resolve Renderers
const ResolvedAggregatedComponent = column.Aggregated || (!column.aggregate ? AggregatedComponent : column.Cell)
const ResolvedExpanderComponent = column.Expander || ExpanderComponent
// Is this column pivoted?
if (pivotBy && column.pivot) {
// Make it expandable
expandable = cellInfo.subRows
cellInfo.expandable = cellInfo.subRows
interactionProps = {
onClick: onExpanderClick
}
// Is this column a branch?
isBranch = rowInfo.rowValues[pivotIDKey] === column.id &&
isBranch = rowInfo.row[pivotIDKey] === column.id &&
cellInfo.subRows
// Should this column be blank?
isPreview = pivotBy.indexOf(column.id) >= pivotBy.indexOf(rowInfo.rowValues[pivotIDKey]) &&
isPreview = pivotBy.indexOf(column.id) > pivotBy.indexOf(rowInfo.row[pivotIDKey]) &&
cellInfo.subRows
// Resolve Pivot Renderers
@@ -545,32 +554,29 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
}, row[pivotValKey])
} else if (isPreview) {
// Show the pivot preview
resolvedCell = _.normalizeComponent(ResolvedAggregateComponent, {
...cellInfo,
value
}, value)
resolvedCell = _.normalizeComponent(ResolvedAggregatedComponent, cellInfo, value)
} else {
resolvedCell = null
}
} else if (cellInfo.aggregated) {
resolvedCell = _.normalizeComponent(ResolvedAggregateComponent, {
...cellInfo,
value
}, value)
resolvedCell = _.normalizeComponent(ResolvedAggregatedComponent, cellInfo, value)
}
// Expander onClick event
if (column.expander) {
resolvedCell = _.normalizeComponent(ResolvedExpanderComponent, {
...cellInfo,
value
})
expandable = true
resolvedCell = _.normalizeComponent(ResolvedExpanderComponent, cellInfo)
cellInfo.expandable = true
interactionProps = {
onClick: onExpanderClick
}
if (cellInfo.subRows) {
resolvedCell = null
if (pivotBy) {
console.log(cellInfo)
if (cellInfo.groupedByPivot) {
resolvedCell = null
}
if (!cellInfo.subRows && !SubComponent) {
resolvedCell = null
}
}
}
@@ -581,7 +587,7 @@ export default class ReactTable extends Methods(Lifecycle(Component)) {
className={classnames(
classes,
!show && 'hidden',
expandable && 'rt-expandable',
cellInfo.expandable && 'rt-expandable',
(isBranch || isPreview) && 'rt-pivot'
)}
style={{
+4 -4
View File
@@ -18,7 +18,7 @@ export default Base => class extends Base {
if ((oldState.showFilters !== newState.showFilters) ||
(oldState.showFilters !== newState.showFilters)) {
newState.filtering = newState.defaultFiltering
newState.filters = newState.defaultFilters
}
// Props that trigger a data update
@@ -28,7 +28,7 @@ export default Base => class extends Base {
oldState.pivotBy !== newState.pivotBy ||
oldState.sorting !== newState.sorting ||
oldState.showFilters !== newState.showFilters ||
oldState.filtering !== newState.filtering
oldState.filters !== newState.filters
) {
this.setStateWithData(this.getDataModel(newState))
}
@@ -59,14 +59,14 @@ export default Base => class extends Base {
if (
(oldState.frozen && !newResolvedState.frozen) ||
oldState.sorting !== newResolvedState.sorting ||
oldState.filtering !== newResolvedState.filtering ||
oldState.filters !== newResolvedState.filters ||
oldState.showFilters !== newResolvedState.showFilters ||
(!newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData)
) {
// Handle collapseOnSortingChange & collapseOnDataChange
if (
(oldState.sorting !== newResolvedState.sorting && this.props.collapseOnSortingChange) ||
(oldState.filtering !== newResolvedState.filtering) ||
(oldState.filters !== newResolvedState.filters) ||
(oldState.showFilters !== newResolvedState.showFilters) ||
(!newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData && this.props.collapseOnDataChange)
) {
+37 -20
View File
@@ -20,6 +20,11 @@ export default Base => class extends Base {
pivotIDKey,
pivotValKey,
subRowsKey,
aggregatedKey,
nestingLevelKey,
originalKey,
indexKey,
groupedByPivotKey,
SubComponent
} = newState
@@ -50,7 +55,6 @@ export default Base => class extends Base {
if (column.expander) {
dcol = {
...this.props.column,
Header: this.props.ExpanderComponent,
...this.props.expanderDefaults,
...column
}
@@ -189,17 +193,23 @@ export default Base => class extends Base {
}
// Access the data
let resolvedData = data.map((d, i) => {
const accessRow = (d, i, level = 0) => {
const row = {
__original: d,
__index: i
[originalKey]: d,
[indexKey]: i,
[subRowsKey]: d[subRowsKey],
[nestingLevelKey]: level
}
allDecoratedColumns.forEach(column => {
if (column.expander) return
row[column.id] = column.accessor(d)
})
if (row[subRowsKey]) {
row[subRowsKey] = row[subRowsKey].map((d, i) => accessRow(d, i, level + 1))
}
return row
})
}
let resolvedData = data.map((d, i) => accessRow(d, i))
// If pivoting, recursively group the data
const aggregate = (rows) => {
@@ -227,7 +237,9 @@ export default Base => class extends Base {
[pivotIDKey]: keys[i],
[pivotValKey]: key,
[keys[i]]: key,
[subRowsKey]: value
[subRowsKey]: value,
[nestingLevelKey]: i,
[groupedByPivotKey]: true
}
})
// Recurse into the subRows
@@ -236,6 +248,7 @@ export default Base => class extends Base {
return {
...rowGroup,
[subRowsKey]: subRows,
[aggregatedKey]: true,
...aggregate(subRows)
}
})
@@ -258,7 +271,7 @@ export default Base => class extends Base {
const {
manual,
sorting,
filtering,
filters,
showFilters,
defaultFilterMethod,
resolvedData,
@@ -280,7 +293,7 @@ export default Base => class extends Base {
this.filterData(
resolvedData,
showFilters,
filtering,
filters,
defaultFilterMethod,
allVisibleColumns
),
@@ -302,11 +315,11 @@ export default Base => class extends Base {
return _.getFirstDefined(this.state[key], this.props[key])
}
filterData (data, showFilters, filtering, defaultFilterMethod, allVisibleColumns) {
filterData (data, showFilters, filters, defaultFilterMethod, allVisibleColumns) {
let filteredData = data
if (showFilters && filtering.length) {
filteredData = filtering.reduce(
if (showFilters && filters.length) {
filteredData = filters.reduce(
(filteredSoFar, nextFilter) => {
return filteredSoFar.filter(
(row) => {
@@ -340,7 +353,7 @@ export default Base => class extends Base {
}
return {
...row,
[this.props.subRowsKey]: this.filterData(row[this.props.subRowsKey], showFilters, filtering, defaultFilterMethod, allVisibleColumns)
[this.props.subRowsKey]: this.filterData(row[this.props.subRowsKey], showFilters, filters, defaultFilterMethod, allVisibleColumns)
}
}).filter(row => {
if (!row[this.props.subRowsKey]) {
@@ -528,15 +541,11 @@ export default Base => class extends Base {
}
filterColumn (column, value) {
const {filtering} = this.getResolvedState()
const {onFilterChange} = this.props
if (onFilterChange) {
return onFilterChange(column, value)
}
const {filters} = this.getResolvedState()
const {onFiltersChange} = this.props
// Remove old filter first if it exists
const newFiltering = (filtering || []).filter(x => {
const newFiltering = (filters || []).filter(x => {
if (x.id !== column.id) {
return true
}
@@ -549,8 +558,16 @@ export default Base => class extends Base {
})
}
onFiltersChange && onFiltersChange(newFiltering, column, value)
// If filters is being controlled, do not manage state internally
if (this.props.filters) {
this.fireFetchData()
return
}
this.setStateWithData({
filtering: newFiltering
filters: newFiltering
}, () => {
this.fireFetchData()
})
+20 -15
View File
@@ -39,7 +39,8 @@ class ControlledTable extends React.Component {
page: 0,
pageSize: 10,
expandedRows: {},
resizing: []
resizing: [],
filters: []
}
}
render () {
@@ -50,23 +51,27 @@ class ControlledTable extends React.Component {
className='-striped -highlight'
data={data}
columns={columns}
sorting={this.state.sorting}
onSortingChange={sorting => this.setState({sorting})}
page={this.state.page}
onPageChange={page => this.setState({page})}
pageSize={this.state.pageSize}
onPageSizeChange={(pageSize, page) => this.setState({page, pageSize})}
expandedRows={this.state.expandedRows}
onExpandRow={(expandedRows) => this.setState({expandedRows})}
resizing={this.state.resizing}
onResize={resizing => this.setState({resizing})}
pivotBy={['lastName']}
showFilters
// Controlled Props
sorting={this.state.sorting}
page={this.state.page}
pageSize={this.state.pageSize}
expandedRows={this.state.expandedRows}
resizing={this.state.resizing}
filters={this.state.filters}
// Callbacks
onSortingChange={sorting => this.setState({sorting})}
onPageChange={page => this.setState({page})}
onPageSizeChange={(pageSize, page) => this.setState({page, pageSize})}
onExpandRow={(expandedRows) => this.setState({expandedRows})}
onResize={resizing => this.setState({resizing})}
onFiltersChange={filters => this.setState({filters})}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: For simplicity, multi-sort is not implemented in this demo</em>
</div>
<br />
<pre><code><strong>this.state ===</strong> {JSON.stringify(this.state, null, 2)}</code></pre>
<br />
<CodeHighlight>{() => getCode()}</CodeHighlight>
</div>
)
+5 -5
View File
@@ -14,13 +14,13 @@ const rawData = _.map(_.range(3424), d => {
})
// Now let's mock the server. It's job is simple: use the table model to sort and return the page data
const requestData = (pageSize, page, sorting, filtering) => {
const requestData = (pageSize, page, sorting, filters) => {
return new Promise((resolve, reject) => {
// On the server, you'll likely use SQL or noSQL or some other query language to do this.
// For this mock, we'll just use lodash
let filteredData = rawData
if (filtering.length) {
filteredData = filtering.reduce(
if (filters.length) {
filteredData = filters.reduce(
(filteredSoFar, nextFilter) => {
return filteredSoFar.filter(
(row) => {
@@ -63,7 +63,7 @@ const ServerSide = React.createClass({
// You can set the `loading` prop of the table to true to use the built-in one or show you're own loading bar if you want.
this.setState({loading: true})
// Request the data however you want. Here, we'll use our mocked service we created earlier
requestData(state.pageSize, state.page, state.sorting, state.filtering)
requestData(state.pageSize, state.page, state.sorting, state.filters)
.then((res) => {
// Now just get the rows of data to your React Table (and update anything else like total pages or loading)
this.setState({
@@ -136,7 +136,7 @@ export default React.createClass({
pageSize: state.pageSize,
page: state.page,
sorting: state.sorting,
filtering: state.filtering
filters: state.filters
})
.then((res) => {
// Now update your state!
+8 -1
View File
@@ -10,7 +10,14 @@ export default () => {
return {
firstName: namor.generate({ words: 1, numLen: 0 }),
lastName: namor.generate({ words: 1, numLen: 0 }),
age: Math.floor(Math.random() * 30)
age: Math.floor(Math.random() * 30),
children: _.map(_.range(10), d => {
return {
firstName: namor.generate({ words: 1, numLen: 0 }),
lastName: namor.generate({ words: 1, numLen: 0 }),
age: Math.floor(Math.random() * 30)
}
})
}
})
+111
View File
@@ -0,0 +1,111 @@
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import CodeHighlight from './components/codeHighlight'
import ReactTable from '../src/index'
export default () => {
const data = _.map(_.range(5553), d => {
const children = _.map(_.range(10), d => {
const grandChildren = _.map(_.range(10), d => {
return {
age: Math.floor(Math.random() * 30)
}
})
return {
firstName: namor.generate({ words: 1, numLen: 0 }),
age: (ages => {
return Math.round(ages.reduce((p, c) => p + c, 0) / ages.length)
})(grandChildren.map(d => d.age)),
aggregated: true,
children: grandChildren
}
})
return {
lastName: namor.generate({ words: 1, numLen: 0 }),
firstName: children.map(d => d.firstName).join(', '),
age: (ages => {
return Math.round(ages.reduce((p, c) => p + c, 0) / ages.length)
})(children.map(d => d.age)),
aggregated: true,
children
}
})
const columns = [{
expander: true
}, {
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
subRowsKey='children'
aggregatedKey='aggregated'
pivotBy={['lastName']}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
<CodeHighlight>{() => getCode()}</CodeHighlight>
</div>
)
}
function getCode () {
return `
import ReactTable from 'react-table'
// Create some column definitions
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
// Display your table!
return (
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
/>
)
`
}