Compare commits

...

42 Commits

Author SHA1 Message Date
AllenFang
b8c9712e91 fix wrong story code 2019-12-09 20:01:09 +08:00
Mark J. Lehman
e4589eb358 Update package.json (#1189) 2019-12-09 19:46:10 +08:00
AllenFang
a07b2da00a fix #1144 2019-12-07 16:40:26 +08:00
AllenFang
2068f518f6 fix #1180 2019-12-07 16:01:35 +08:00
AllenFang
47d6eb097a fix #1188 2019-12-07 14:29:20 +08:00
AllenFang
76f4795400 add story for caption table for bootstrap4 2019-12-07 13:29:19 +08:00
Allen
ee829eb924 Merge pull request #1190 from Ymbere/fix_1185
Fix 1185
2019-12-07 13:26:54 +08:00
AllenFang
ae34c44547 fix wrong story example code 2019-12-05 20:42:05 +08:00
Ymbere Xavier
b99a277595 Fix issue with caption on bootstrap 4
Add new prop to check if bootstrap is used
Update component in order to return a custom caption when bootstrap4
is in use
2019-12-04 02:24:08 -02:00
Ymbere Xavier
1d13565824 Add new prop to Caption component
Add new prop of Caption component in order to check if
bootstrap is in use
2019-12-04 02:23:27 -02:00
AllenFang
8ecdbf611b fix #1169 2019-11-23 15:56:14 +08:00
AllenFang
4a340c714b fix #1168 2019-11-23 14:35:45 +08:00
AllenFang
6d13a86512 fix #1157 2019-11-16 14:23:50 +08:00
AllenFang
b5d536b8f4 fix #1146 2019-11-16 14:11:16 +08:00
Allen
e667317fbe Merge pull request #1136 from Ymbere/master
Set custom class or style for disabled/non-selectable. [Improve #1135]
2019-11-13 20:40:04 +08:00
Ymbere Xavier
d4ffc11f7e Update storybook with the new props examples 2019-11-09 21:15:39 -02:00
Ymbere Xavier
3c6aaacbce Update row-selection.md documentation
Add `nonSelectableStyle` documentation
Add `nonSelectableClasses` documentation
2019-11-09 21:15:39 -02:00
Ymbere Xavier
defcd04b52 Update bootstrap-table and row-consumer
Add new props to the bootstrap-table, nonSelectableStyle and
nonSelectableClasses

Update row-consume in order to support custom styles and classes
for non selectable rows
2019-11-09 21:15:39 -02:00
AllenFang
7138b68559 fix test cases 2019-11-09 14:49:42 +08:00
AllenFang
e6e7d6f9d2 Merge branch 'aliogaili-master' into develop 2019-10-26 15:23:49 +08:00
AllenFang
909a6e211e close #1005 2019-10-26 15:23:14 +08:00
Ali Ogaili
83c9d69e27 More eslint errors fixing. 2019-10-26 14:31:52 +08:00
Ali Ogaili
aad2ad3823 Fix eslint errors. 2019-10-26 14:31:52 +08:00
Ali Ogaili
9190cfc6d9 fix https://github.com/react-bootstrap-table/react-bootstrap-table2/issues/1005 2019-10-26 14:31:09 +08:00
AllenFang
45b133579b fix #1124 2019-10-26 14:22:44 +08:00
AllenFang
970f7c0d15 update yarn lock file 2019-10-13 13:30:40 +08:00
Mark J. Lehman
def898f636 Avoid exact version lock for classnames (#1107)
Fixes #732
2019-10-13 13:22:46 +08:00
AllenFang
18caf0ac8d try to fix #1085 and #1098 2019-09-29 16:36:32 +08:00
AllenFang
1b9bd63370 fix #1104 2019-09-29 16:30:49 +08:00
AllenFang
b2121fdf24 fix #1099 #1101 2019-09-29 16:19:36 +08:00
AllenFang
4aaf140de5 fix wrong story code 2019-09-29 15:06:11 +08:00
ebfg
569aa0195e Note in defaultSorted docs that only one column is supported. #1083 (#1088) 2019-09-15 14:36:10 +08:00
AllenFang
7d28d46185 enhance footer event 2019-09-07 16:27:18 +08:00
AllenFang
16128e77e6 fix #1077 2019-09-07 16:25:49 +08:00
AllenFang
ec1f96cd1f fix #1082 2019-09-07 15:56:13 +08:00
AllenFang
00b1558df0 fix #1078 2019-09-07 14:44:18 +08:00
AllenFang
4dc5e6099f Merge branch 'chimericdream-master' into develop 2019-08-31 14:19:15 +08:00
AllenFang
d9acbace67 refine #1073 2019-08-31 14:18:55 +08:00
Bill Parrott
7c8bf00cde execute react-codemod on entire codebase to remove warnings on React 16.9.x 2019-08-28 15:32:22 -05:00
Bill Parrott
63df43a1e0 Merge branch 'master' of github.com:react-bootstrap-table/react-bootstrap-table2 2019-08-28 14:32:12 -05:00
Bill Parrott
2b410fb8ac Merge branch 'master' of github.com:react-bootstrap-table/react-bootstrap-table2 2019-08-12 13:34:14 -05:00
Bill Parrott
e31b5eb691 set tabindex to 0 for table headers; fixes #955 2019-06-03 09:26:15 -05:00
70 changed files with 1700 additions and 348 deletions

View File

@@ -28,10 +28,12 @@
* [rowClasses](#rowClasses) * [rowClasses](#rowClasses)
* [rowEvents](#rowEvents) * [rowEvents](#rowEvents)
* [hiddenRows](#hiddenRows) * [hiddenRows](#hiddenRows)
* [sort](#sort)
* [defaultSorted](#defaultSorted) * [defaultSorted](#defaultSorted)
* [defaultSortDirection](#defaultSortDirection) * [defaultSortDirection](#defaultSortDirection)
* [pagination](#pagination) * [pagination](#pagination)
* [filter](#filter) * [filter](#filter)
* [filterPosition](filterPosition)
* [onTableChange](#onTableChange) * [onTableChange](#onTableChange)
* [onDataSizeChange](#onDataSizeChange) * [onDataSizeChange](#onDataSizeChange)
@@ -198,6 +200,27 @@ const hiddenRows = [1, 4];
<BootstrapTable data={ data } columns={ columns } hiddenRows={ hiddenRows } /> <BootstrapTable data={ data } columns={ columns } hiddenRows={ hiddenRows } />
``` ```
### <a name='sort'>sort - [Object]</a>
Two cases you probably need to configure `sort` prop:
#### Manage sorting state
You can give `dataField` and `order` to specify the sorting state in table, For example
```js
<BootstrapTable sort={ { dataField: 'price', order: 'asc' } }>
```
#### One-time sorting configuration
In earily version, we only can configure [`sortCaret`](./columns.md#sortCaret) and [`sortFunc` ](./columns.md#sortFunc) per column. But they are same in most of cases.
So here we give you a chance to just setup these prop in one time.
```js
<BootstrapTable sort={ {
sortCaret: ...
sortFunc: ...
} }>
```
### <a name='defaultSorted'>defaultSorted - [Array]</a> ### <a name='defaultSorted'>defaultSorted - [Array]</a>
`defaultSorted` accept an object array which allow you to define the default sort columns when first render. `defaultSorted` accept an object array which allow you to define the default sort columns when first render.
@@ -208,6 +231,8 @@ const defaultSorted = [{
}]; }];
``` ```
**Note**: Only the first column is sorted currently, see #1083.
### <a name='defaultSortDirection'>defaultSortDirection - [String]</a> ### <a name='defaultSortDirection'>defaultSortDirection - [String]</a>
Default sort direction when user click on header column at first time, available value is `asc` and `desc`. Default is `desc`. Default sort direction when user click on header column at first time, available value is `asc` and `desc`. Default is `desc`.
@@ -327,6 +352,9 @@ Following is a shape of `newState`
} }
``` ```
### <a name='filterPosition'>filterPosition - [String]</a>
Available value is `inline`, `top` and `bottom`, default is `inline`. This prop decide where `react-bootstrap-table` render column filter.
### <a name='onDataSizeChange'>onDataSizeChange - [Function]</a> ### <a name='onDataSizeChange'>onDataSizeChange - [Function]</a>
This callback function will be called only when data size change by search/filter etc. This function have one argument which is an object contains below props: This callback function will be called only when data size change by search/filter etc. This function have one argument which is an object contains below props:

View File

@@ -13,6 +13,7 @@ Available properties in a column object:
* [formatExtraData](#formatExtraData) * [formatExtraData](#formatExtraData)
* [type](#type) * [type](#type)
* [sort](#sort) * [sort](#sort)
* [sortValue](#sortValue)
* [sortFunc](#sortFunc) * [sortFunc](#sortFunc)
* [sortCaret](#sortCaret) * [sortCaret](#sortCaret)
* [onSort](#onSort) * [onSort](#onSort)
@@ -141,8 +142,42 @@ Specify the data type on column. Available value so far is `string`, `number`, `
## <a name='sort'>column.sort - [Bool]</a> ## <a name='sort'>column.sort - [Bool]</a>
Enable the column sort via a `true` value given. Enable the column sort via a `true` value given.
## <a name='sortValue'>column.sortValue - [Function]</a>
`column.sortValue` only work when `column.sort` enabled. This prop allow you to replace the value when table sorting.
For example, consider following data:
```js
const types = ['Cloud Service', 'Message Service', 'Add Service', 'Edit Service', 'Money'];
const data = [{id: 1, type: 2}, {id: 2, type: 1}, {id: 3, type:0}];
const columns = [{
dataField: 'id',
text: 'Job ID'
}, {
dataField: 'type',
text: 'Job Type'
sort: true,
formatter: (cell, row) => types[cell]
}]
```
In above case, when user try to sort Job Type column which will sort the original value: 0, 1, 2 but we display the type name via [`column.formatter`](#formatter), which will lead confuse because we are sorting by type value instead of type name. So `sortValue` is a way for you to decide what kind of value should be adopted when sorting on a specify column:
```js
const columns = [{
dataField: 'id',
text: 'Job ID'
}, {
dataField: 'type',
text: 'Job Type'
sort: true,
formatter: (cell, row) => types[cell],
sortValue: (cell, row) => types[cell] // we use type name to sort.
}]
```
## <a name='sortFunc'>column.sortFunc - [Function]</a> ## <a name='sortFunc'>column.sortFunc - [Function]</a>
`column.sortFunc` only work when `column.sort` is enable. `sortFunc` allow you to define your sorting algorithm. This callback function accept six arguments: `column.sortFunc` only work when `column.sort` enabled. `sortFunc` allow you to define your sorting algorithm. This callback function accept six arguments:
```js ```js
{ {
@@ -421,7 +456,7 @@ If the events is not listed above, the callback function will only pass the `eve
{ {
// omit... // omit...
headerEvents: { headerEvents: {
onClick: e => { ... } onClick: (e, column, columnIndex) => { ... }
} }
} }
``` ```
@@ -631,7 +666,7 @@ It's also available to custom via a callback function:
{ {
// omit... // omit...
footerEvents: { footerEvents: {
onClick: e => { ... } onClick: (e, column, columnIndex) => { ... }
} }
} }
``` ```

View File

@@ -1,6 +1,6 @@
# Row selection # Row selection
`react-bootstrap-table2` supports the row selection feature. By passing prop `selectRow` to enable row selection. When you enable this feature, `react-bootstrap-table2` will prepend a new selection column. `react-bootstrap-table2` supports the row selection feature. By passing prop `selectRow` to enable row selection. When you enable this feature, `react-bootstrap-table2` will prepend a new selection column.
## Required ## Required
* [mode (**required**)](#mode) * [mode (**required**)](#mode)
@@ -11,6 +11,8 @@
* [classes)](#classes) * [classes)](#classes)
* [bgColor](#bgColor) * [bgColor](#bgColor)
* [nonSelectable)](#nonSelectable) * [nonSelectable)](#nonSelectable)
* [nonSelectableStyle](#nonSelectableStyle)
* [nonSelectableClasses](#nonSelectableClasses)
* [clickToSelect)](#clickToSelect) * [clickToSelect)](#clickToSelect)
* [clickToExpand)](#clickToExpand) * [clickToExpand)](#clickToExpand)
* [clickToEdit](#clickToEdit) * [clickToEdit](#clickToEdit)
@@ -139,6 +141,54 @@ const selectRow = {
}; };
``` ```
### <a name='nonSelectableStyle'>selectRow.nonSelectableStyle - [Object | Function]</a>
This prop allow you to customize the non selectable rows. `selectRow.nonSelectableStyle` accepts an style object
and a callback function for more flexible customization.
### Style Object
```js
const selectRow = {
mode: 'checkbox',
nonSelectable: [1, 3 ,5],
nonSelectableStyle: { backgroundColor: 'gray' }
};
```
### Callback Function
```js
const selectRow = {
mode: 'checkbox',
nonSelectable: [1, 3 ,5],
nonSelectableStyle: (row, rowIndex) => { return ...; }
};
```
### <a name='nonSelectableClasses'>selectRow.nonSelectableClasses - [String | Function]</a>
This prop allow you to set a custom class for the non selectable rows, or use a callback function for more
flexible customization
### String
```js
const selectRow = {
mode: 'checkbox',
nonSelectable: [1, 3 ,5],
nonSelectableClasses: 'my-class'
};
```
### Callback Function
```js
const selectRow = {
mode: 'checkbox',
nonSelectable: [1, 3 ,5],
nonSelectableClasses: (row, rowIndex) => { return ...; }
};
```
### <a name='clickToSelect'>selectRow.clickToSelect - [Bool]</a> ### <a name='clickToSelect'>selectRow.clickToSelect - [Bool]</a>
Allow user to select row by clicking on the row. Allow user to select row by clicking on the row.
@@ -149,7 +199,7 @@ const selectRow = {
}; };
``` ```
> Note: When you also enable [cellEdit](./cell-edit.md), the `selectRow.clickToSelect` will deactivate the functionality of cell editing > Note: When you also enable [cellEdit](./cell-edit.md), the `selectRow.clickToSelect` will deactivate the functionality of cell editing
> If you want to click on row to select row and edit cell simultaneously, you are suppose to enable [`selectRow.clickToEdit`](#clickToEdit) > If you want to click on row to select row and edit cell simultaneously, you are suppose to enable [`selectRow.clickToEdit`](#clickToEdit)
### <a name='clickToExpand'>selectRow.clickToExpand - [Bool]</a> ### <a name='clickToExpand'>selectRow.clickToExpand - [Bool]</a>
@@ -307,7 +357,7 @@ const selectRow = {
mode: 'checkbox', mode: 'checkbox',
onSelectAll: (isSelect, rows, e) => { onSelectAll: (isSelect, rows, e) => {
if (isSelect && SOME_CONDITION) { if (isSelect && SOME_CONDITION) {
return [1, 3, 4]; // finally, key 1, 3, 4 will being selected return [1, 3, 4]; // finally, key 1, 3, 4 will being selected
} }
} }
}; };

View File

@@ -80,7 +80,7 @@
"webpack-dev-server": "2.7.1" "webpack-dev-server": "2.7.1"
}, },
"dependencies": { "dependencies": {
"classnames": "2.2.5", "classnames": "^2.2.5",
"prop-types": "15.5.10", "prop-types": "15.5.10",
"react": "16.4.0", "react": "16.4.0",
"react-dom": "16.4.0", "react-dom": "16.4.0",

View File

@@ -1,5 +1,8 @@
/* eslint disable-next-line: 0 */
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
/* eslint react/require-default-props: 0 */ /* eslint react/require-default-props: 0 */
/* eslint camelcase: 0 */
/* eslint react/no-unused-prop-types: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { CLICK_TO_CELL_EDIT, DBCLICK_TO_CELL_EDIT } from './const'; import { CLICK_TO_CELL_EDIT, DBCLICK_TO_CELL_EDIT } from './const';
@@ -43,7 +46,7 @@ export default (
}; };
} }
componentWillReceiveProps(nextProps) { UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.cellEdit && isRemoteCellEdit()) { if (nextProps.cellEdit && isRemoteCellEdit()) {
if (nextProps.cellEdit.options.errorMessage) { if (nextProps.cellEdit.options.errorMessage) {
this.setState(() => ({ this.setState(() => ({

View File

@@ -2,6 +2,7 @@
/* eslint no-return-assign: 0 */ /* eslint no-return-assign: 0 */
/* eslint class-methods-use-this: 0 */ /* eslint class-methods-use-this: 0 */
/* eslint jsx-a11y/no-noninteractive-element-interactions: 0 */ /* eslint jsx-a11y/no-noninteractive-element-interactions: 0 */
/* eslint camelcase: 0 */
import React, { Component } from 'react'; import React, { Component } from 'react';
import cs from 'classnames'; import cs from 'classnames';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -51,7 +52,11 @@ export default (_, onStartEdit) =>
}; };
} }
componentWillReceiveProps({ message }) { componentWillUnmount() {
this.clearTimer();
}
UNSAFE_componentWillReceiveProps({ message }) {
if (_.isDefined(message)) { if (_.isDefined(message)) {
this.createTimer(); this.createTimer();
this.setState(() => ({ this.setState(() => ({
@@ -60,10 +65,6 @@ export default (_, onStartEdit) =>
} }
} }
componentWillUnmount() {
this.clearTimer();
}
clearTimer() { clearTimer() {
if (this.indicatorTimer) { if (this.indicatorTimer) {
clearTimeout(this.indicatorTimer); clearTimeout(this.indicatorTimer);

View File

@@ -117,7 +117,7 @@ describe('CellEditContext', () => {
wrapper = shallow(shallowContext()); wrapper = shallow(shallowContext());
wrapper.setState(initialState); wrapper.setState(initialState);
wrapper.render(); wrapper.render();
wrapper.instance().componentWillReceiveProps({}); wrapper.instance().UNSAFE_componentWillReceiveProps({});
}); });
it('should not set state.message', () => { it('should not set state.message', () => {
@@ -138,7 +138,7 @@ describe('CellEditContext', () => {
wrapper = shallow(shallowContext()); wrapper = shallow(shallowContext());
wrapper.setState(initialState); wrapper.setState(initialState);
wrapper.render(); wrapper.render();
wrapper.instance().componentWillReceiveProps({ wrapper.instance().UNSAFE_componentWillReceiveProps({
cellEdit: cellEditFactory(defaultCellEdit) cellEdit: cellEditFactory(defaultCellEdit)
}); });
}); });
@@ -164,7 +164,7 @@ describe('CellEditContext', () => {
wrapper = shallow(shallowContext(defaultCellEdit, true)); wrapper = shallow(shallowContext(defaultCellEdit, true));
wrapper.setState(initialState); wrapper.setState(initialState);
wrapper.render(); wrapper.render();
wrapper.instance().componentWillReceiveProps({ wrapper.instance().UNSAFE_componentWillReceiveProps({
cellEdit: cellEditFactory({ cellEdit: cellEditFactory({
...defaultCellEdit, ...defaultCellEdit,
errorMessage: message errorMessage: message
@@ -190,7 +190,7 @@ describe('CellEditContext', () => {
beforeEach(() => { beforeEach(() => {
wrapper = shallow(shallowContext(defaultCellEdit, true)); wrapper = shallow(shallowContext(defaultCellEdit, true));
wrapper.setState(initialState); wrapper.setState(initialState);
wrapper.instance().componentWillReceiveProps({ wrapper.instance().UNSAFE_componentWillReceiveProps({
cellEdit: cellEditFactory({ ...defaultCellEdit }) cellEdit: cellEditFactory({ ...defaultCellEdit })
}); });
wrapper.update(); wrapper.update();

View File

@@ -0,0 +1,49 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const CaptionElement = () => <h3 style={{ borderRadius: '0.25em', textAlign: 'center', color: 'purple', border: '1px solid purple', padding: '0.5em' }}>Component as Header</h3>;
<BootstrapTable bootstrap4 keyField="id" data={ products } caption="Plain text header" columns={ columns } />
<BootstrapTable bootstrap4 keyField="id" data={ products } caption={<CaptionElement />} columns={ columns } />
`;
const Caption = () => <h3 style={ { borderRadius: '0.25em', textAlign: 'center', color: 'purple', border: '1px solid purple', padding: '0.5em' } }>Component as Header</h3>;
export default () => (
<div>
<BootstrapTable bootstrap4 keyField="id" data={ products } caption="Plain text header" columns={ columns } />
<BootstrapTable bootstrap4 keyField="id" data={ products } caption={ <Caption /> } columns={ columns } />
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -0,0 +1,114 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const products = productsGenerator(8);
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name',
filter: textFilter()
}, {
dataField: 'price',
text: 'Product Price',
filter: textFilter()
}];
const sourceCode1 = `\
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
const columns = [{
dataField: 'id',
text: 'Product ID',
}, {
dataField: 'name',
text: 'Product Name',
filter: textFilter()
}, {
dataField: 'price',
text: 'Product Price',
filter: textFilter()
}];
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="top"
/>
`;
const sourceCode2 = `\
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
const columns = [{
dataField: 'id',
text: 'Product ID',
}, {
dataField: 'name',
text: 'Product Name',
filter: textFilter()
}, {
dataField: 'price',
text: 'Product Price',
filter: textFilter()
}];
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="bottom"
/>
`;
const selectRow = {
mode: 'checkbox',
clickToSelect: true
};
const expandRow = {
renderer: row => (
<div>
<p>{ `This Expand row is belong to rowKey ${row.id}` }</p>
<p>You can render anything here, also you can add additional data on every row object</p>
<p>expandRow.renderer callback will pass the origin row object to you</p>
</div>
),
showExpandColumn: true,
expandColumnPosition: 'right'
};
export default () => (
<div>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="top"
expandRow={ expandRow }
selectRow={ selectRow }
/>
<Code>{ sourceCode1 }</Code>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="bottom"
expandRow={ expandRow }
selectRow={ selectRow }
/>
<Code>{ sourceCode2 }</Code>
</div>
);

View File

@@ -8,14 +8,17 @@ const products = productsGenerator(8);
const columns = [{ const columns = [{
dataField: 'id', dataField: 'id',
text: 'Product ID' text: 'Product ID',
footer: 'hello'
}, { }, {
dataField: 'name', dataField: 'name',
text: 'Product Name', text: 'Product Name',
footer: 'hello',
filter: textFilter() filter: textFilter()
}, { }, {
dataField: 'price', dataField: 'price',
text: 'Product Price', text: 'Product Price',
footer: 'hello',
filter: textFilter() filter: textFilter()
}]; }];
@@ -39,6 +42,11 @@ const columns = [{
<BootstrapTable keyField='id' data={ products } columns={ columns } filter={ filterFactory() } /> <BootstrapTable keyField='id' data={ products } columns={ columns } filter={ filterFactory() } />
`; `;
const selectRow = {
mode: 'checkbox',
clickToSelect: true
};
export default () => ( export default () => (
<div> <div>
<BootstrapTable <BootstrapTable
@@ -46,6 +54,8 @@ export default () => (
data={ products } data={ products }
columns={ columns } columns={ columns }
filter={ filterFactory() } filter={ filterFactory() }
filterPosition="bottom"
selectRow={ selectRow }
/> />
<Code>{ sourceCode }</Code> <Code>{ sourceCode }</Code>
</div> </div>

View File

@@ -40,7 +40,13 @@ const columns = [{
keyField="id" keyField="id"
data={ products } data={ products }
columns={ columns } columns={ columns }
exportCSV exportCSV={ {
fileName: 'custom.csv',
separator: '|',
ignoreHeader: true,
noAutoBOM: false,
blobType: 'text/csv;charset=ansi'
} }
> >
{ {
props => ( props => (
@@ -64,7 +70,8 @@ export default () => (
fileName: 'custom.csv', fileName: 'custom.csv',
separator: '|', separator: '|',
ignoreHeader: true, ignoreHeader: true,
noAutoBOM: false noAutoBOM: false,
blobType: 'text/csv;charset=ansi'
} } } }
> >
{ {

View File

@@ -36,11 +36,12 @@ const columns = [{
const MyExportCSV = (props) => { const MyExportCSV = (props) => {
const handleClick = () => { const handleClick = () => {
props.onExport(); // passing my custom data
props.onExport(products.filter(r => r.id > 2));
}; };
return ( return (
<div> <div>
<button className="btn btn-success" onClick={ handleClick }>Export to CSV</button> <button className="btn btn-success" onClick={ handleClick }>Only export Product ID bigger than 2</button>
</div> </div>
); );
}; };

View File

@@ -0,0 +1,88 @@
/* eslint react/prop-types: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import ToolkitProvider, { CSVExport } from 'react-bootstrap-table2-toolkit';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const { ExportCSVButton } = CSVExport;
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID',
footer: 'Footer 1'
}, {
dataField: 'name',
text: 'Product Name',
footer: '',
footerFormatter: column => column.text
}, {
dataField: 'price',
text: 'Product Price',
footer: columnData => columnData.reduce((acc, item) => acc + item, 0)
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
import ToolkitProvider, { CSVExport } from 'react-bootstrap-table2-toolkit';
const { ExportCSVButton } = CSVExport;
const columns = [{
dataField: 'id',
text: 'Product ID',
footer: 'Footer 1'
}, {
dataField: 'name',
text: 'Product Name',
footer: 'Footer 2'
}, {
dataField: 'price',
text: 'Product Price',
footer: 'Footer 3'
}];
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
exportCSV={ {
ignoreFooter: false
} }
>
{
props => (
<div>
<ExportCSVButton { ...props.csvProps }>Export CSV!!</ExportCSVButton>
<hr />
<BootstrapTable { ...props.baseProps } />
</div>
)
}
</ToolkitProvider>
`;
export default () => (
<div>
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
exportCSV={ {
ignoreFooter: false
} }
>
{
props => (
<div>
<ExportCSVButton { ...props.csvProps }>Export CSV!!</ExportCSVButton>
<hr />
<BootstrapTable { ...props.baseProps } />
</div>
)
}
</ToolkitProvider>
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -12,7 +12,7 @@ const columns = [{
dataField: 'id', dataField: 'id',
text: 'Product ID', text: 'Product ID',
footerEvents: { footerEvents: {
onClick: () => alert('Click on Product ID footer column') onClick: (e, column, columnIndex) => alert(`Click on Product ID header column, columnIndex: ${columnIndex}`)
}, },
footer: 'Footer 1' footer: 'Footer 1'
}, { }, {
@@ -32,7 +32,7 @@ const columns = [{
dataField: 'id', dataField: 'id',
text: 'Product ID', text: 'Product ID',
footerEvents: { footerEvents: {
onClick: () => alert('Click on Product ID footer column') onClick: (e, column, columnIndex) => alert('Click on Product ID footer column')
}, },
footer: 'Footer 1' footer: 'Footer 1'
}, { }, {

View File

@@ -12,7 +12,7 @@ const columns = [{
dataField: 'id', dataField: 'id',
text: 'Product ID', text: 'Product ID',
headerEvents: { headerEvents: {
onClick: () => alert('Click on Product ID header column') onClick: (e, column, columnIndex) => alert(`Click on Product ID header column, columnIndex: ${columnIndex}`)
} }
}, { }, {
dataField: 'name', dataField: 'name',
@@ -29,7 +29,7 @@ const columns = [{
dataField: 'id', dataField: 'id',
text: 'Product ID', text: 'Product ID',
headerEvents: { headerEvents: {
onClick: () => alert('Click on Product ID header column') onClick: (e, column, columnIndex) => alert('Click on Product ID header column')
} }
}, { }, {
dataField: 'name', dataField: 'name',

View File

@@ -0,0 +1,61 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const selectRow = {
mode: 'checkbox',
clickToSelect: true,
nonSelectable: [0, 2, 4],
nonSelectableClasses: 'row-index-bigger-than-2101'
};
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const selectRow = {
mode: 'checkbox',
clickToSelect: true,
nonSelectable: [0, 2, 4],
nonSelectableClasses: 'row-index-bigger-than-2101'
};
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
selectRow={ selectRow }
/>
`;
export default () => (
<div>
<BootstrapTable keyField="id" data={ products } columns={ columns } selectRow={ selectRow } />
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -0,0 +1,61 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const selectRow = {
mode: 'checkbox',
clickToSelect: true,
nonSelectable: [0, 2, 4],
nonSelectableStyle: { backgroundColor: 'gray' }
};
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const selectRow = {
mode: 'checkbox',
clickToSelect: true,
nonSelectable: [0, 2, 4],
nonSelectableStyle: { backgroundColor: 'gray' }
};
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
selectRow={ selectRow }
/>
`;
export default () => (
<div>
<BootstrapTable keyField="id" data={ products } columns={ columns } selectRow={ selectRow } />
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -0,0 +1,116 @@
/* eslint react/prop-types: 0 */
/* eslint no-unused-vars: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import ToolkitProvider, { Search } from 'react-bootstrap-table2-toolkit';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const { SearchBar } = Search;
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
import ToolkitProvider, { Search } from 'react-bootstrap-table2-toolkit';
const { SearchBar } = Search;
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
// Implement startWith instead of contain
function customMatchFunc({
searchText,
value,
column,
row
}) {
if (typeof value !== 'undefined') {
return value.startsWith(searchText);
}
return false;
}
export default () => (
<div>
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
search={ { customMatchFunc } }
>
{
props => (
<div>
<h3>Input something at below input field:</h3>
<SearchBar { ...props.searchProps } />
<hr />
<BootstrapTable
{ ...props.baseProps }
/>
</div>
)
}
</ToolkitProvider>
<Code>{ sourceCode }</Code>
</div>
);
`;
// Implement startWith instead of contain
function customMatchFunc({
searchText,
value,
column,
row
}) {
if (typeof value !== 'undefined') {
return `${value}`.toLowerCase().startsWith(searchText.toLowerCase());
}
return false;
}
export default () => (
<div>
<h1>Custom a search match function by startWith instead of contain</h1>
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
search={ { onColumnMatch: customMatchFunc } }
>
{
props => (
<div>
<h3>Input something at below input field:</h3>
<SearchBar { ...props.searchProps } />
<hr />
<BootstrapTable
{ ...props.baseProps }
/>
</div>
)
}
</ToolkitProvider>
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -0,0 +1,78 @@
/* eslint no-unused-vars: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { jobsGenerator1 } from 'utils/common';
const jobs = jobsGenerator1(8);
const types = ['Cloud Service', 'Message Service', 'Add Service', 'Edit Service', 'Money'];
const columns = [{
dataField: 'id',
text: 'Job ID'
}, {
dataField: 'name',
text: 'Job Name'
}, {
dataField: 'owner',
text: 'Job Owner'
}, {
dataField: 'type',
text: 'Job Type',
sort: true,
formatter: (cell, row) => types[cell],
sortValue: (cell, row) => types[cell]
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
const types = ['Cloud Service', 'Message Service', 'Add Service', 'Edit Service', 'Money'];
const columns = [{
dataField: 'id',
text: 'Job ID'
}, {
dataField: 'name',
text: 'Job Name'
}, {
dataField: 'owner',
text: 'Job Owner'
}, {
dataField: 'type',
text: 'Job Type',
sort: true,
formatter: (cell, row) => types[cell],
sortValue: (cell, row) => types[cell]
}];
<BootstrapTable keyField='id' data={ products } columns={ columns } />
`;
export default class Test extends React.Component {
constructor(props) {
super(props);
this.state = { data: jobs };
}
handleClick = () => {
this.setState(() => {
const newProducts = jobsGenerator1(21);
return {
data: newProducts
};
});
}
render() {
return (
<div>
<button className="btn btn-default" onClick={ this.handleClick }>Change Data</button>
<BootstrapTable keyField="id" data={ this.state.data } columns={ columns } />
<Code>{ sourceCode }</Code>
</div>
);
}
}

View File

@@ -0,0 +1,98 @@
/* eslint no-unused-vars: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID',
sort: true
}, {
dataField: 'name',
text: 'Product Name',
sort: true
}, {
dataField: 'price',
text: 'Product Price'
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = [{
dataField: 'id',
text: 'Product ID',
sort: true
}, {
dataField: 'name',
text: 'Product Name',
sort: true
}, {
dataField: 'price',
text: 'Product Price'
}];
class OnetimeSortConfiguration extends React.Component {
sortFunc = (a, b, order, dataField) => {
if (order === 'asc') {
return b - a;
}
return a - b; // desc
}
render() {
const sortOption = {
// No need to configure sortFunc per column
sortFunc: this.sortFunc,
// No need to configure sortCaret per column
sortCaret: (order, column) => {
if (!order) return (<span>&nbsp;&nbsp;Desc/Asc</span>);
else if (order === 'asc') return (<span>&nbsp;&nbsp;Desc/<font color="red">Asc</font></span>);
else if (order === 'desc') return (<span>&nbsp;&nbsp;<font color="red">Desc</font>/Asc</span>);
return null;
}
};
return (
<div>
<button className="btn btn-default" onClick={ this.handleClick }>Change Data</button>
<BootstrapTable keyField="id" data={ products } columns={ columns } sort={ sortOption } />
<Code>{ sourceCode }</Code>
</div>
);
}
}
`;
export default class OnetimeSortConfiguration extends React.Component {
sortFunc = (a, b, order, dataField) => {
if (order === 'asc') {
return b - a;
}
return a - b; // desc
}
render() {
const sortOption = {
sortFunc: this.sortFunc,
sortCaret: (order, column) => {
if (!order) return (<span>&nbsp;&nbsp;Desc/Asc</span>);
else if (order === 'asc') return (<span>&nbsp;&nbsp;Desc/<font color="red">Asc</font></span>);
else if (order === 'desc') return (<span>&nbsp;&nbsp;<font color="red">Desc</font>/Asc</span>);
return null;
}
};
return (
<div>
<h3>Reverse Sorting Table</h3>
<BootstrapTable keyField="id" data={ products } columns={ columns } sort={ sortOption } />
<Code>{ sourceCode }</Code>
</div>
);
}
}

View File

@@ -0,0 +1,118 @@
/* eslint no-console: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const products = productsGenerator();
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
class SortManagement extends React.Component {
state = {
field: null,
order: null
}
handleSort = (field, order) => {
this.setState({
field,
order
});
}
handleSortById = () => {
this.setState({
field: 'id',
order: 'desc'
});
}
render() {
const columns = [{
dataField: 'id',
text: 'Product ID',
sort: true,
onSort: this.handleSort
}, {
dataField: 'name',
text: 'Product Name',
sort: true,
onSort: this.handleSort
}, {
dataField: 'price',
text: 'Product Price'
}];
return (
<div>
<button className="btn btn-danger" onClick={ this.handleSortById }>Sort By ID</button>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
sort={ {
dataField: this.state.field,
order: this.state.order
} }
/>
<Code>{ sourceCode }</Code>
</div>
);
}
}
`;
export default class SortManagement extends React.Component {
state = {
field: null,
order: null
}
handleSort = (field, order) => {
this.setState({
field,
order
});
}
handleSortById = () => {
this.setState({
field: 'id',
order: 'desc'
});
}
render() {
const columns = [{
dataField: 'id',
text: 'Product ID',
sort: true,
onSort: this.handleSort
}, {
dataField: 'name',
text: 'Product Name',
sort: true,
onSort: this.handleSort
}, {
dataField: 'price',
text: 'Product Price'
}];
return (
<div>
<button className="btn btn-danger" onClick={ this.handleSortById }>Sort By ID</button>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
sort={ {
dataField: this.state.field,
order: this.state.order
} }
/>
<Code>{ sourceCode }</Code>
</div>
);
}
}

View File

@@ -29,6 +29,11 @@ export const withOnSale = rows => rows.map((row) => {
return row; return row;
}); });
export const withRandomPrice = rows => rows.map((row) => {
row.price = Math.floor((Math.random() * 10) + 2000);
return row;
});
export const productsQualityGenerator = (quantity = 5, factor = 0) => export const productsQualityGenerator = (quantity = 5, factor = 0) =>
Array.from({ length: quantity }, (value, index) => ({ Array.from({ length: quantity }, (value, index) => ({
id: index + factor, id: index + factor,

View File

@@ -18,6 +18,7 @@ import TabIndexCellTable from 'examples/basic/tabindex-column';
// bootstrap 4 // bootstrap 4
import Bootstrap4DefaultSortTable from 'examples/bootstrap4/sort'; import Bootstrap4DefaultSortTable from 'examples/bootstrap4/sort';
import Bootstrap4CaptionTable from 'examples/bootstrap4/caption-table';
import Bootstrap4RowSelectionTable from 'examples/bootstrap4/row-selection'; import Bootstrap4RowSelectionTable from 'examples/bootstrap4/row-selection';
import Bootstrap4PaginationTable from 'examples/bootstrap4/pagination'; import Bootstrap4PaginationTable from 'examples/bootstrap4/pagination';
import Bootstrap4ColumnToggleTable from 'examples/bootstrap4/column-toggle'; import Bootstrap4ColumnToggleTable from 'examples/bootstrap4/column-toggle';
@@ -92,6 +93,7 @@ import AdvanceCustomFilter from 'examples/column-filter/advance-custom-filter';
import ClearAllFilters from 'examples/column-filter/clear-all-filters'; import ClearAllFilters from 'examples/column-filter/clear-all-filters';
import FilterHooks from 'examples/column-filter/filter-hooks'; import FilterHooks from 'examples/column-filter/filter-hooks';
import CustomFilterLogic from 'examples/column-filter/custom-filter-logic'; import CustomFilterLogic from 'examples/column-filter/custom-filter-logic';
import FilterPosition from 'examples/column-filter/filter-position';
// work on rows // work on rows
import RowStyleTable from 'examples/rows/row-style'; import RowStyleTable from 'examples/rows/row-style';
@@ -104,6 +106,9 @@ import EnableSortTable from 'examples/sort/enable-sort-table';
import DefaultSortTable from 'examples/sort/default-sort-table'; import DefaultSortTable from 'examples/sort/default-sort-table';
import DefaultSortDirectionTable from 'examples/sort/default-sort-direction'; import DefaultSortDirectionTable from 'examples/sort/default-sort-direction';
import SortEvents from 'examples/sort/sort-events'; import SortEvents from 'examples/sort/sort-events';
import SortManagement from 'examples/sort/sort-management';
import OneTimeSortConfiguration from 'examples/sort/one-time-sort-configuration';
import CustomSortValue from 'examples/sort/custom-sort-value';
import CustomSortTable from 'examples/sort/custom-sort-table'; import CustomSortTable from 'examples/sort/custom-sort-table';
import CustomSortCaretTable from 'examples/sort/custom-sort-caret'; import CustomSortCaretTable from 'examples/sort/custom-sort-caret';
import HeaderSortingClassesTable from 'examples/sort/header-sorting-classes'; import HeaderSortingClassesTable from 'examples/sort/header-sorting-classes';
@@ -150,6 +155,8 @@ import HeaderStyleTable from 'examples/row-selection/header-style';
import HideSelectAllTable from 'examples/row-selection/hide-select-all'; import HideSelectAllTable from 'examples/row-selection/hide-select-all';
import CustomSelectionTable from 'examples/row-selection/custom-selection'; import CustomSelectionTable from 'examples/row-selection/custom-selection';
import NonSelectableRowsTable from 'examples/row-selection/non-selectable-rows'; import NonSelectableRowsTable from 'examples/row-selection/non-selectable-rows';
import NonSelectableRowsStyleTable from 'examples/row-selection/non-selectable-rows-style';
import NonSelectableRowsClassTable from 'examples/row-selection/non-selectable-rows-class';
import SelectionBgColorTable from 'examples/row-selection/selection-bgcolor'; import SelectionBgColorTable from 'examples/row-selection/selection-bgcolor';
import SelectionHooks from 'examples/row-selection/selection-hooks'; import SelectionHooks from 'examples/row-selection/selection-hooks';
import HideSelectionColumnTable from 'examples/row-selection/hide-selection-column'; import HideSelectionColumnTable from 'examples/row-selection/hide-selection-column';
@@ -195,6 +202,7 @@ import FullyCustomSearch from 'examples/search/fully-custom-search';
import SearchFormattedData from 'examples/search/search-formatted'; import SearchFormattedData from 'examples/search/search-formatted';
import CustomSearchValue from 'examples/search/custom-search-value'; import CustomSearchValue from 'examples/search/custom-search-value';
import SearchableColumn from 'examples/search/searchable-column'; import SearchableColumn from 'examples/search/searchable-column';
import CustomMatchFunction from 'examples/search/custom-match-function';
// CSV // CSV
import ExportCSV from 'examples/csv'; import ExportCSV from 'examples/csv';
@@ -207,6 +215,7 @@ import CSVColumnType from 'examples/csv/csv-column-type';
import CustomCSVButton from 'examples/csv/custom-csv-button'; import CustomCSVButton from 'examples/csv/custom-csv-button';
import ExportCustomData from 'examples/csv/export-custom-data'; import ExportCustomData from 'examples/csv/export-custom-data';
import CustomCSV from 'examples/csv/custom-csv'; import CustomCSV from 'examples/csv/custom-csv';
import ExportTableFooter from 'examples/csv/export-footer';
// Column toggle // Column toggle
import BasicColumnToggle from 'examples/column-toggle'; import BasicColumnToggle from 'examples/column-toggle';
@@ -263,6 +272,7 @@ storiesOf('Basic Table', module)
storiesOf('Bootstrap 4', module) storiesOf('Bootstrap 4', module)
.addDecorator(bootstrapStyle(BOOTSTRAP_VERSION.FOUR)) .addDecorator(bootstrapStyle(BOOTSTRAP_VERSION.FOUR))
.add('Sort table with bootstrap 4', () => <Bootstrap4DefaultSortTable />) .add('Sort table with bootstrap 4', () => <Bootstrap4DefaultSortTable />)
.add('Table Caption bootstrap 4', () => <Bootstrap4CaptionTable />)
.add('Row selection table with bootstrap 4', () => <Bootstrap4RowSelectionTable />) .add('Row selection table with bootstrap 4', () => <Bootstrap4RowSelectionTable />)
.add('Pagination table with bootstrap 4', () => <Bootstrap4PaginationTable />) .add('Pagination table with bootstrap 4', () => <Bootstrap4PaginationTable />)
.add('Column Toggle with bootstrap 4', () => <Bootstrap4ColumnToggleTable />) .add('Column Toggle with bootstrap 4', () => <Bootstrap4ColumnToggleTable />)
@@ -312,6 +322,7 @@ storiesOf('Column Filter', module)
.add('Number Filter with Default Value', () => <NumberFilterWithDefaultValue />) .add('Number Filter with Default Value', () => <NumberFilterWithDefaultValue />)
.add('Date Filter', () => <DateFilter />) .add('Date Filter', () => <DateFilter />)
.add('Date Filter with Default Value', () => <DateFilterWithDefaultValue />) .add('Date Filter with Default Value', () => <DateFilterWithDefaultValue />)
.add('Filter Position', () => <FilterPosition />)
.add('Custom Text Filter', () => <CustomTextFilter />) .add('Custom Text Filter', () => <CustomTextFilter />)
.add('Custom Select Filter', () => <CustomSelectFilter />) .add('Custom Select Filter', () => <CustomSelectFilter />)
.add('Custom Number Filter', () => <CustomNumberFilter />) .add('Custom Number Filter', () => <CustomNumberFilter />)
@@ -356,6 +367,9 @@ storiesOf('Sort Table', module)
.add('Default Sort Table', () => <DefaultSortTable />) .add('Default Sort Table', () => <DefaultSortTable />)
.add('Default Sort Direction Table', () => <DefaultSortDirectionTable />) .add('Default Sort Direction Table', () => <DefaultSortDirectionTable />)
.add('Sort Events', () => <SortEvents />) .add('Sort Events', () => <SortEvents />)
.add('Sort Management', () => <SortManagement />)
.add('One-time Sort Configuation', () => <OneTimeSortConfiguration />)
.add('Custom Sort Value', () => <CustomSortValue />)
.add('Custom Sort Fuction', () => <CustomSortTable />) .add('Custom Sort Fuction', () => <CustomSortTable />)
.add('Custom Sort Caret', () => <CustomSortCaretTable />) .add('Custom Sort Caret', () => <CustomSortCaretTable />)
.add('Custom Classes on Sorting Header Column', () => <HeaderSortingClassesTable />) .add('Custom Classes on Sorting Header Column', () => <HeaderSortingClassesTable />)
@@ -405,6 +419,8 @@ storiesOf('Row Selection', module)
.add('Custom Selection', () => <CustomSelectionTable />) .add('Custom Selection', () => <CustomSelectionTable />)
.add('Selection Background Color', () => <SelectionBgColorTable />) .add('Selection Background Color', () => <SelectionBgColorTable />)
.add('Not Selectabled Rows', () => <NonSelectableRowsTable />) .add('Not Selectabled Rows', () => <NonSelectableRowsTable />)
.add('Not Selectabled Rows Style', () => <NonSelectableRowsStyleTable />)
.add('Not Selectabled Rows Class', () => <NonSelectableRowsClassTable />)
.add('Selection Hooks', () => <SelectionHooks />) .add('Selection Hooks', () => <SelectionHooks />)
.add('Hide Selection Column', () => <HideSelectionColumnTable />) .add('Hide Selection Column', () => <HideSelectionColumnTable />)
.add('Custom Selection Column Style', () => <SelectionColumnStyleTable />) .add('Custom Selection Column Style', () => <SelectionColumnStyleTable />)
@@ -451,7 +467,8 @@ storiesOf('Table Search', module)
.add('Searchable Column', () => <SearchableColumn />) .add('Searchable Column', () => <SearchableColumn />)
.add('Fully Custom Search', () => <FullyCustomSearch />) .add('Fully Custom Search', () => <FullyCustomSearch />)
.add('Search Formatted Value', () => <SearchFormattedData />) .add('Search Formatted Value', () => <SearchFormattedData />)
.add('Custom Search Value', () => <CustomSearchValue />); .add('Custom Search Value', () => <CustomSearchValue />)
.add('Custom match function', () => <CustomMatchFunction />);
storiesOf('Column Toggle', module) storiesOf('Column Toggle', module)
.addDecorator(bootstrapStyle()) .addDecorator(bootstrapStyle())
@@ -472,7 +489,8 @@ storiesOf('Export CSV', module)
.add('CSV Column Type', () => <CSVColumnType />) .add('CSV Column Type', () => <CSVColumnType />)
.add('Custom CSV Button', () => <CustomCSVButton />) .add('Custom CSV Button', () => <CustomCSVButton />)
.add('Export Custom Data', () => <ExportCustomData />) .add('Export Custom Data', () => <ExportCustomData />)
.add('Custom CSV', () => <CustomCSV />); .add('Custom CSV', () => <CustomCSV />)
.add('Export Table Footer', () => <ExportTableFooter />);
storiesOf('EmptyTableOverlay', module) storiesOf('EmptyTableOverlay', module)
.addDecorator(bootstrapStyle()) .addDecorator(bootstrapStyle())

View File

@@ -330,3 +330,29 @@ Following properties is valid in `FILTER_TYPES`:
* NUMBER * NUMBER
* DATE * DATE
* MULTISELECT * MULTISELECT
### Position
Default filter is rendered inside the table column header, but you can choose to render them as a row by `filterPosition`:
#### Render in the top of table body
```js
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="top"
/>
```
#### Render in the bottom of table body
```js
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="bottom"
/>
```

View File

@@ -1,6 +1,7 @@
/* eslint react/require-default-props: 0 */ /* eslint react/require-default-props: 0 */
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
/* eslint no-return-assign: 0 */ /* eslint no-return-assign: 0 */
/* eslint camelcase: 0 */
import React, { Component } from 'react'; import React, { Component } from 'react';
import { PropTypes } from 'prop-types'; import { PropTypes } from 'prop-types';
@@ -41,16 +42,16 @@ class TextFilter extends Component {
} }
} }
componentWillReceiveProps(nextProps) { componentWillUnmount() {
this.cleanTimer();
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.defaultValue !== this.props.defaultValue) { if (nextProps.defaultValue !== this.props.defaultValue) {
this.applyFilter(nextProps.defaultValue); this.applyFilter(nextProps.defaultValue);
} }
} }
componentWillUnmount() {
this.cleanTimer();
}
filter(e) { filter(e) {
e.stopPropagation(); e.stopPropagation();
this.cleanTimer(); this.cleanTimer();

View File

@@ -1,5 +1,6 @@
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
/* eslint react/require-default-props: 0 */ /* eslint react/require-default-props: 0 */
/* eslint camelcase: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -37,15 +38,6 @@ export default (
} }
} }
componentWillReceiveProps(nextProps) {
// let nextData = nextProps.data;
if (!isRemoteFiltering() && !_.isEqual(nextProps.data, this.data)) {
this.doFilter(nextProps, this.isEmitDataChange);
} else {
this.data = nextProps.data;
}
}
onFilter(column, filterType, initialize = false) { onFilter(column, filterType, initialize = false) {
return (filterVal) => { return (filterVal) => {
// watch out here if migration to context API, #334 // watch out here if migration to context API, #334
@@ -90,6 +82,15 @@ export default (
return this.data; return this.data;
} }
UNSAFE_componentWillReceiveProps(nextProps) {
// let nextData = nextProps.data;
if (!isRemoteFiltering() && !_.isEqual(nextProps.data, this.data)) {
this.doFilter(nextProps, this.isEmitDataChange);
} else {
this.data = nextProps.data;
}
}
doFilter(props, ignoreEmitDataChange = false) { doFilter(props, ignoreEmitDataChange = false) {
const { dataChangeListener, data, columns } = props; const { dataChangeListener, data, columns } = props;
const result = filters(data, columns, _)(this.currFilters); const result = filters(data, columns, _)(this.currFilters);

View File

@@ -144,7 +144,7 @@ describe('Text Filter', () => {
<TextFilter onFilter={ onFilter } column={ column } /> <TextFilter onFilter={ onFilter } column={ column } />
); );
instance = wrapper.instance(); instance = wrapper.instance();
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
}); });
it('should setting state correctly when props.defaultValue is changed', () => { it('should setting state correctly when props.defaultValue is changed', () => {

View File

@@ -21,8 +21,9 @@ class PaginationDataProvider extends Provider {
isRemotePagination: PropTypes.func.isRequired isRemotePagination: PropTypes.func.isRequired
} }
componentWillReceiveProps(nextProps) { // eslint-disable-next-line camelcase, react/sort-comp
super.componentWillReceiveProps(nextProps); UNSAFE_componentWillReceiveProps(nextProps) {
super.UNSAFE_componentWillReceiveProps(nextProps);
const { currSizePerPage } = this; const { currSizePerPage } = this;
const { custom, onPageChange } = nextProps.pagination.options; const { custom, onPageChange } = nextProps.pagination.options;

View File

@@ -1,4 +1,5 @@
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
/* eslint camelcase: 0 */
import React, { Component } from 'react'; import React, { Component } from 'react';
import pageResolver from './page-resolver'; import pageResolver from './page-resolver';
@@ -12,7 +13,7 @@ export default WrappedComponent =>
this.state = this.initialState(); this.state = this.initialState();
} }
componentWillReceiveProps(nextProps) { UNSAFE_componentWillReceiveProps(nextProps) {
const { dataSize, currSizePerPage } = nextProps; const { dataSize, currSizePerPage } = nextProps;
if (currSizePerPage !== this.props.currSizePerPage || dataSize !== this.props.dataSize) { if (currSizePerPage !== this.props.currSizePerPage || dataSize !== this.props.dataSize) {
const totalPages = this.calculateTotalPage(currSizePerPage, dataSize); const totalPages = this.calculateTotalPage(currSizePerPage, dataSize);

View File

@@ -1,6 +1,7 @@
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
/* eslint react/require-default-props: 0 */ /* eslint react/require-default-props: 0 */
/* eslint no-lonely-if: 0 */ /* eslint no-lonely-if: 0 */
/* eslint camelcase: 0 */
import React from 'react'; import React from 'react';
import EventEmitter from 'events'; import EventEmitter from 'events';
import Const from './const'; import Const from './const';
@@ -45,23 +46,6 @@ class StateProvider extends React.Component {
this.dataChangeListener.on('filterChanged', this.handleDataSizeChange); this.dataChangeListener.on('filterChanged', this.handleDataSizeChange);
} }
componentWillReceiveProps(nextProps) {
const { custom } = nextProps.pagination.options;
// user should align the page when the page is not fit to the data size when remote enable
if (this.isRemotePagination() || custom) {
if (typeof nextProps.pagination.options.page !== 'undefined') {
this.currPage = nextProps.pagination.options.page;
}
if (typeof nextProps.pagination.options.sizePerPage !== 'undefined') {
this.currSizePerPage = nextProps.pagination.options.sizePerPage;
}
if (typeof nextProps.pagination.options.totalSize !== 'undefined') {
this.dataSize = nextProps.pagination.options.totalSize;
}
}
}
getPaginationProps = () => { getPaginationProps = () => {
const { pagination: { options }, bootstrap4 } = this.props; const { pagination: { options }, bootstrap4 } = this.props;
const { currPage, currSizePerPage, dataSize } = this; const { currPage, currSizePerPage, dataSize } = this;
@@ -113,6 +97,23 @@ class StateProvider extends React.Component {
getPaginationRemoteEmitter = () => this.remoteEmitter || this.props.remoteEmitter; getPaginationRemoteEmitter = () => this.remoteEmitter || this.props.remoteEmitter;
UNSAFE_componentWillReceiveProps(nextProps) {
const { custom } = nextProps.pagination.options;
// user should align the page when the page is not fit to the data size when remote enable
if (this.isRemotePagination() || custom) {
if (typeof nextProps.pagination.options.page !== 'undefined') {
this.currPage = nextProps.pagination.options.page;
}
if (typeof nextProps.pagination.options.sizePerPage !== 'undefined') {
this.currSizePerPage = nextProps.pagination.options.sizePerPage;
}
if (typeof nextProps.pagination.options.totalSize !== 'undefined') {
this.dataSize = nextProps.pagination.options.totalSize;
}
}
}
isRemotePagination = () => { isRemotePagination = () => {
const e = {}; const e = {};
this.remoteEmitter.emit('isRemotePagination', e); this.remoteEmitter.emit('isRemotePagination', e);

View File

@@ -174,7 +174,7 @@ describe('PaginationDataContext', () => {
data: [], data: [],
pagination: { ...defaultPagination } pagination: { ...defaultPagination }
}; };
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
}); });
it('should reset currPage to first page', () => { it('should reset currPage to first page', () => {
@@ -195,7 +195,7 @@ describe('PaginationDataContext', () => {
data: [], data: [],
pagination: { ...defaultPagination, options: { onPageChange } } pagination: { ...defaultPagination, options: { onPageChange } }
}; };
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
}); });
it('should call options.onPageChange correctly', () => { it('should call options.onPageChange correctly', () => {

View File

@@ -164,13 +164,13 @@ describe('paginationHandler', () => {
}); });
it('should setting correct state.totalPages', () => { it('should setting correct state.totalPages', () => {
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
expect(instance.state.totalPages).toEqual( expect(instance.state.totalPages).toEqual(
instance.calculateTotalPage(nextProps.currSizePerPage)); instance.calculateTotalPage(nextProps.currSizePerPage));
}); });
it('should setting correct state.lastPage', () => { it('should setting correct state.lastPage', () => {
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
const totalPages = instance.calculateTotalPage(nextProps.currSizePerPage); const totalPages = instance.calculateTotalPage(nextProps.currSizePerPage);
expect(instance.state.lastPage).toEqual( expect(instance.state.lastPage).toEqual(
instance.calculateLastPage(totalPages)); instance.calculateLastPage(totalPages));
@@ -186,13 +186,13 @@ describe('paginationHandler', () => {
}); });
it('should setting correct state.totalPages', () => { it('should setting correct state.totalPages', () => {
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
expect(instance.state.totalPages).toEqual( expect(instance.state.totalPages).toEqual(
instance.calculateTotalPage(nextProps.currSizePerPage, nextProps.dataSize)); instance.calculateTotalPage(nextProps.currSizePerPage, nextProps.dataSize));
}); });
it('should setting correct state.lastPage', () => { it('should setting correct state.lastPage', () => {
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
const totalPages = instance.calculateTotalPage( const totalPages = instance.calculateTotalPage(
nextProps.currSizePerPage, nextProps.dataSize); nextProps.currSizePerPage, nextProps.dataSize);
expect(instance.state.lastPage).toEqual( expect(instance.state.lastPage).toEqual(

View File

@@ -156,7 +156,7 @@ describe('PaginationStateContext', () => {
data, data,
pagination: { ...defaultPagination, options: { page: 3, sizePerPage: 5, totalSize: 50 } } pagination: { ...defaultPagination, options: { page: 3, sizePerPage: 5, totalSize: 50 } }
}; };
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
}); });
it('should always reset currPage and currSizePerPage', () => { it('should always reset currPage and currSizePerPage', () => {
@@ -181,7 +181,7 @@ describe('PaginationStateContext', () => {
options: { page: 3, sizePerPage: 5, custom: true, totalSize: 50 } options: { page: 3, sizePerPage: 5, custom: true, totalSize: 50 }
} }
}; };
instance.componentWillReceiveProps(nextProps); instance.UNSAFE_componentWillReceiveProps(nextProps);
}); });
it('should always reset currPage and currSizePerPage', () => { it('should always reset currPage and currSizePerPage', () => {

View File

@@ -98,6 +98,33 @@ Accept a string that will be used for default searching when first time table re
</ToolkitProvider> </ToolkitProvider>
``` ```
#### onColumnMatch - [function]
Acccpt a function which will be called when table try to match every cells when search happening. This function accept an object like below example:
```js
function onColumnMatch({
searchText,
value,
column,
row
}) {
// implement your custom match logic on every cell value
}
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
search={ {
onColumnMatch
} }
>
// ...
</ToolkitProvider>
```
> Notes: You have to return `true` when your match logic is positive and vice versa.
#### searchFormatted - [bool] #### searchFormatted - [bool]
If you want to search on the formatted data, you are supposed to enable this props. `react-bootstrap-table2` will check if you define the `column.formatter` when doing search. If you want to search on the formatted data, you are supposed to enable this props. `react-bootstrap-table2` will check if you define the `column.formatter` when doing search.
@@ -182,6 +209,9 @@ Custom the csv file separator.
#### ignoreHeader - [bool] #### ignoreHeader - [bool]
Default is `false`. Give true to avoid to attach the csv header. Default is `false`. Give true to avoid to attach the csv header.
#### ignoreFooter - [bool]
Default is `true`. Give `false` to attach the table footer if enabled.
#### noAutoBOM - [bool] #### noAutoBOM - [bool]
Default is `true`. Default is `true`.

View File

@@ -28,6 +28,7 @@ class ToolkitProvider extends statelessDecorator(React.Component) {
fileName: PropTypes.string, fileName: PropTypes.string,
separator: PropTypes.string, separator: PropTypes.string,
ignoreHeader: PropTypes.bool, ignoreHeader: PropTypes.bool,
ignoreFooter: PropTypes.bool,
noAutoBOM: PropTypes.bool, noAutoBOM: PropTypes.bool,
blobType: PropTypes.string, blobType: PropTypes.string,
exportAll: PropTypes.bool, exportAll: PropTypes.bool,

View File

@@ -12,17 +12,21 @@ export const getMetaInfo = columns =>
export: column.csvExport === false ? false : true, export: column.csvExport === false ? false : true,
row: Number(column.row) || 0, row: Number(column.row) || 0,
rowSpan: Number(column.rowSpan) || 1, rowSpan: Number(column.rowSpan) || 1,
colSpan: Number(column.colSpan) || 1 colSpan: Number(column.colSpan) || 1,
footer: column.footer,
footerFormatter: column.footerFormatter
})) }))
.filter(_ => _.export); .filter(_ => _.export);
export const transform = ( export const transform = (
data, data,
meta, meta,
getValue, columns,
_,
{ {
separator, separator,
ignoreHeader ignoreHeader,
ignoreFooter
} }
) => { ) => {
const visibleColumns = meta.filter(m => m.export); const visibleColumns = meta.filter(m => m.export);
@@ -37,7 +41,7 @@ export const transform = (
content += data content += data
.map((row, rowIndex) => .map((row, rowIndex) =>
visibleColumns.map((m) => { visibleColumns.map((m) => {
let cellContent = getValue(row, m.field); let cellContent = _.get(row, m.field);
if (m.formatter) { if (m.formatter) {
cellContent = m.formatter(cellContent, row, rowIndex, m.formatExtraData); cellContent = m.formatter(cellContent, row, rowIndex, m.formatExtraData);
} }
@@ -47,6 +51,18 @@ export const transform = (
return cellContent; return cellContent;
}).join(separator)).join('\n'); }).join(separator)).join('\n');
if (!ignoreFooter) {
content += '\n';
content += visibleColumns.map((m, i) => {
if (typeof m.footer === 'function') {
const columnData = _.pluck(data, columns[i].dataField);
return `"${m.footer(columnData, columns[i], i)}"`;
} else if (m.footerFormatter) {
return `"${m.footerFormatter(columns[i], i)}"`;
}
return `"${m.footer}"`;
}).join(separator);
}
return content; return content;
}; };

View File

@@ -4,6 +4,7 @@ const csvDefaultOptions = {
fileName: 'spreadsheet.csv', fileName: 'spreadsheet.csv',
separator: ',', separator: ',',
ignoreHeader: false, ignoreHeader: false,
ignoreFooter: true,
noAutoBOM: true, noAutoBOM: true,
blobType: 'text/plain;charset=utf-8', blobType: 'text/plain;charset=utf-8',
exportAll: true, exportAll: true,
@@ -46,7 +47,7 @@ export default Base =>
data = data.filter(row => !!selections.find(sel => row[keyField] === sel)); data = data.filter(row => !!selections.find(sel => row[keyField] === sel));
} }
const content = transform(data, meta, this._.get, options); const content = transform(data, meta, columns, this._, options);
save(content, options); save(content, options);
} }
}; };

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint no-return-assign: 0 */ /* eslint no-return-assign: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -34,10 +35,6 @@ class SearchBar extends React.Component {
}; };
} }
componentWillReceiveProps(nextProps) {
this.setState({ value: nextProps.searchText });
}
onChangeValue = (e) => { onChangeValue = (e) => {
this.setState({ value: e.target.value }); this.setState({ value: e.target.value });
} }
@@ -50,6 +47,10 @@ class SearchBar extends React.Component {
debounceCallback(); debounceCallback();
} }
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({ value: nextProps.searchText });
}
render() { render() {
const { const {
className, className,

View File

@@ -3,11 +3,13 @@
/* eslint no-continue: 0 */ /* eslint no-continue: 0 */
/* eslint no-lonely-if: 0 */ /* eslint no-lonely-if: 0 */
/* eslint class-methods-use-this: 0 */ /* eslint class-methods-use-this: 0 */
/* eslint camelcase: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
export default (options = { export default (options = {
searchFormatted: false searchFormatted: false,
onColumnMatch: null
}) => ( }) => (
_, _,
isRemoteSearch, isRemoteSearch,
@@ -35,7 +37,17 @@ export default (options = {
this.state = { data: initialData }; this.state = { data: initialData };
} }
componentWillReceiveProps(nextProps) { getSearched() {
return this.state.data;
}
triggerListener(result) {
if (this.props.dataChangeListener) {
this.props.dataChangeListener.emit('filterChanged', result.length);
}
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.searchText !== this.props.searchText) { if (nextProps.searchText !== this.props.searchText) {
if (isRemoteSearch()) { if (isRemoteSearch()) {
handleRemoteSearchChange(nextProps.searchText); handleRemoteSearchChange(nextProps.searchText);
@@ -59,16 +71,6 @@ export default (options = {
} }
} }
getSearched() {
return this.state.data;
}
triggerListener(result) {
if (this.props.dataChangeListener) {
this.props.dataChangeListener.emit('filterChanged', result.length);
}
}
search(props) { search(props) {
const { data, columns } = props; const { data, columns } = props;
const searchText = props.searchText.toLowerCase(); const searchText = props.searchText.toLowerCase();
@@ -82,11 +84,22 @@ export default (options = {
} else if (column.filterValue) { } else if (column.filterValue) {
targetValue = column.filterValue(targetValue, row); targetValue = column.filterValue(targetValue, row);
} }
if (targetValue !== null && typeof targetValue !== 'undefined') { if (options.onColumnMatch) {
targetValue = targetValue.toString().toLowerCase(); if (options.onColumnMatch({
if (targetValue.indexOf(searchText) > -1) { searchText,
value: targetValue,
column,
row
})) {
return true; return true;
} }
} else {
if (targetValue !== null && typeof targetValue !== 'undefined') {
targetValue = targetValue.toString().toLowerCase();
if (targetValue.indexOf(searchText) > -1) {
return true;
}
}
} }
} }
return false; return false;

View File

@@ -36,7 +36,7 @@
} }
], ],
"dependencies": { "dependencies": {
"classnames": "2.2.5", "classnames": "^2.2.5",
"react-transition-group": "2.5.3", "react-transition-group": "2.5.3",
"underscore": "1.9.1" "underscore": "1.9.1"
}, },

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint arrow-body-style: 0 */ /* eslint arrow-body-style: 0 */
import React, { Component } from 'react'; import React, { Component } from 'react';
@@ -5,6 +6,7 @@ import PropTypes from 'prop-types';
import cs from 'classnames'; import cs from 'classnames';
import Header from './header'; import Header from './header';
import Filters from './filters';
import Caption from './caption'; import Caption from './caption';
import Body from './body'; import Body from './body';
import Footer from './footer'; import Footer from './footer';
@@ -18,7 +20,7 @@ class BootstrapTable extends PropsBaseResolver(Component) {
this.validateProps(); this.validateProps();
} }
componentWillReceiveProps(nextProps) { UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.onDataSizeChange && !nextProps.pagination) { if (nextProps.onDataSizeChange && !nextProps.pagination) {
if (nextProps.data.length !== this.props.data.length) { if (nextProps.data.length !== this.props.data.length) {
nextProps.onDataSizeChange({ dataSize: nextProps.data.length }); nextProps.onDataSizeChange({ dataSize: nextProps.data.length });
@@ -64,7 +66,8 @@ class BootstrapTable extends PropsBaseResolver(Component) {
rowEvents, rowEvents,
selectRow, selectRow,
expandRow, expandRow,
cellEdit cellEdit,
filterPosition
} = this.props; } = this.props;
const tableWrapperClass = cs('react-bootstrap-table', wrapperClasses); const tableWrapperClass = cs('react-bootstrap-table', wrapperClasses);
@@ -76,9 +79,13 @@ class BootstrapTable extends PropsBaseResolver(Component) {
[bootstrap4 ? 'table-sm' : 'table-condensed']: condensed [bootstrap4 ? 'table-sm' : 'table-condensed']: condensed
}, classes); }, classes);
const hasFilters = columns.some(col => col.filter || col.filterRenderer);
const hasFooter = _.filter(columns, col => _.has(col, 'footer')).length > 0; const hasFooter = _.filter(columns, col => _.has(col, 'footer')).length > 0;
const tableCaption = (caption && <Caption>{ caption }</Caption>); const tableCaption = (
caption && <Caption bootstrap4={ bootstrap4 }>{ caption }</Caption>
);
return ( return (
<div className={ tableWrapperClass }> <div className={ tableWrapperClass }>
@@ -90,12 +97,27 @@ class BootstrapTable extends PropsBaseResolver(Component) {
sortField={ this.props.sortField } sortField={ this.props.sortField }
sortOrder={ this.props.sortOrder } sortOrder={ this.props.sortOrder }
onSort={ this.props.onSort } onSort={ this.props.onSort }
globalSortCaret={ this.props.sort && this.props.sort.sortCaret }
onFilter={ this.props.onFilter } onFilter={ this.props.onFilter }
currFilters={ this.props.currFilters } currFilters={ this.props.currFilters }
onExternalFilter={ this.props.onExternalFilter } onExternalFilter={ this.props.onExternalFilter }
selectRow={ selectRow } selectRow={ selectRow }
expandRow={ expandRow } expandRow={ expandRow }
filterPosition={ filterPosition }
/> />
{hasFilters && filterPosition !== Const.FILTERS_POSITION_INLINE && (
<Filters
columns={ columns }
className={ this.props.filtersClasses }
onSort={ this.props.onSort }
onFilter={ this.props.onFilter }
currFilters={ this.props.currFilters }
filterPosition={ this.props.filterPosition }
onExternalFilter={ this.props.onExternalFilter }
selectRow={ selectRow }
expandRow={ expandRow }
/>
)}
<Body <Body
data={ this.getData() } data={ this.getData() }
keyField={ keyField } keyField={ keyField }
@@ -134,7 +156,7 @@ BootstrapTable.propTypes = {
remote: PropTypes.oneOfType([PropTypes.bool, PropTypes.shape({ remote: PropTypes.oneOfType([PropTypes.bool, PropTypes.shape({
pagination: PropTypes.bool pagination: PropTypes.bool
})]), })]),
noDataIndication: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), noDataIndication: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
striped: PropTypes.bool, striped: PropTypes.bool,
bordered: PropTypes.bool, bordered: PropTypes.bool,
hover: PropTypes.bool, hover: PropTypes.bool,
@@ -165,6 +187,8 @@ BootstrapTable.propTypes = {
style: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), style: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
classes: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), classes: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
nonSelectable: PropTypes.array, nonSelectable: PropTypes.array,
nonSelectableStyle: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
nonSelectableClasses: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
bgColor: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), bgColor: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
hideSelectColumn: PropTypes.bool, hideSelectColumn: PropTypes.bool,
selectionRenderer: PropTypes.func, selectionRenderer: PropTypes.func,
@@ -198,11 +222,23 @@ BootstrapTable.propTypes = {
rowEvents: PropTypes.object, rowEvents: PropTypes.object,
rowClasses: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), rowClasses: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
headerClasses: PropTypes.string, headerClasses: PropTypes.string,
filtersClasses: PropTypes.string,
filterPosition: PropTypes.oneOf([
Const.FILTERS_POSITION_TOP,
Const.FILTERS_POSITION_INLINE,
Const.FILTERS_POSITION_BOTTOM
]),
footerClasses: PropTypes.string, footerClasses: PropTypes.string,
defaultSorted: PropTypes.arrayOf(PropTypes.shape({ defaultSorted: PropTypes.arrayOf(PropTypes.shape({
dataField: PropTypes.string.isRequired, dataField: PropTypes.string.isRequired,
order: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]).isRequired order: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]).isRequired
})), })),
sort: PropTypes.shape({
dataField: PropTypes.string,
order: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]),
sortFunc: PropTypes.func,
sortCaret: PropTypes.func
}),
defaultSortDirection: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]), defaultSortDirection: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]),
overlay: PropTypes.func, overlay: PropTypes.func,
onTableChange: PropTypes.func, onTableChange: PropTypes.func,
@@ -239,7 +275,8 @@ BootstrapTable.defaultProps = {
cellEdit: { cellEdit: {
mode: null, mode: null,
nonEditableRows: [] nonEditableRows: []
} },
filterPosition: Const.FILTERS_POSITION_INLINE
}; };
export default BootstrapTable; export default BootstrapTable;

View File

@@ -4,16 +4,22 @@ import PropTypes from 'prop-types';
const Caption = (props) => { const Caption = (props) => {
if (!props.children) return null; if (!props.children) return null;
return (
<caption>{ props.children }</caption> const caption = props.bootstrap4 ? (
<caption style={ { captionSide: 'top' } }>{props.children}</caption>
) : (
<caption>{props.children}</caption>
); );
return caption;
}; };
Caption.propTypes = { Caption.propTypes = {
children: PropTypes.oneOfType([ children: PropTypes.oneOfType([
PropTypes.node, PropTypes.node,
PropTypes.string PropTypes.string
]) ]),
bootstrap4: PropTypes.bool
}; };
export default Caption; export default Caption;

View File

@@ -17,8 +17,8 @@ export default ExtendBase =>
createDefaultEventHandler(cb) { createDefaultEventHandler(cb) {
return (e) => { return (e) => {
const { column, columnIndex } = this.props; const { column, columnIndex, index } = this.props;
cb(e, column, columnIndex); cb(e, column, typeof columnIndex !== 'undefined' ? columnIndex : index);
}; };
} }

View File

@@ -12,5 +12,8 @@ export default {
TYPE_STRING: 'string', TYPE_STRING: 'string',
TYPE_NUMBER: 'number', TYPE_NUMBER: 'number',
TYPE_BOOLEAN: 'bool', TYPE_BOOLEAN: 'bool',
TYPE_DATE: 'date' TYPE_DATE: 'date',
FILTERS_POSITION_INLINE: 'inline',
FILTERS_POSITION_TOP: 'top',
FILTERS_POSITION_BOTTOM: 'bottom'
}; };

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
import React, { Component } from 'react'; import React, { Component } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -12,10 +13,6 @@ export default () => {
state = { data: this.props.data }; state = { data: this.props.data };
componentWillReceiveProps(nextProps) {
this.setState(() => ({ data: nextProps.data }));
}
getData = (filterProps, searchProps, sortProps, paginationProps) => { getData = (filterProps, searchProps, sortProps, paginationProps) => {
if (paginationProps) return paginationProps.data; if (paginationProps) return paginationProps.data;
else if (sortProps) return sortProps.data; else if (sortProps) return sortProps.data;
@@ -24,6 +21,10 @@ export default () => {
return this.props.data; return this.props.data;
} }
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState(() => ({ data: nextProps.data }));
}
render() { render() {
return ( return (
<DataContext.Provider <DataContext.Provider

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint no-return-assign: 0 */ /* eslint no-return-assign: 0 */
/* eslint no-param-reassign: 0 */ /* eslint no-param-reassign: 0 */
/* eslint class-methods-use-this: 0 */ /* eslint class-methods-use-this: 0 */
@@ -83,7 +84,7 @@ const withContext = Base =>
} }
} }
componentWillReceiveProps(nextProps) { UNSAFE_componentWillReceiveProps(nextProps) {
if (!nextProps.pagination && this.props.pagination) { if (!nextProps.pagination && this.props.pagination) {
this.PaginationContext = null; this.PaginationContext = null;
} }
@@ -246,6 +247,7 @@ const withContext = Base =>
ref={ n => this.sortContext = n } ref={ n => this.sortContext = n }
defaultSorted={ this.props.defaultSorted } defaultSorted={ this.props.defaultSorted }
defaultSortDirection={ this.props.defaultSortDirection } defaultSortDirection={ this.props.defaultSortDirection }
sort={ this.props.sort }
data={ rootProps.getData(filterProps, searchProps) } data={ rootProps.getData(filterProps, searchProps) }
> >
<this.SortContext.Consumer> <this.SortContext.Consumer>

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -16,7 +17,11 @@ class RowExpandProvider extends React.Component {
state = { expanded: this.props.expandRow.expanded || [], state = { expanded: this.props.expandRow.expanded || [],
isClosing: this.props.expandRow.isClosing || [] }; isClosing: this.props.expandRow.isClosing || [] };
componentWillReceiveProps(nextProps) { onClosed = (closedRow) => {
this.setState({ isClosing: this.state.isClosing.filter(value => value !== closedRow) });
};
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.expandRow) { if (nextProps.expandRow) {
const nextExpanded = nextProps.expandRow.expanded || this.state.expanded; const nextExpanded = nextProps.expandRow.expanded || this.state.expanded;
const isClosing = this.state.expanded.reduce((acc, cur) => { const isClosing = this.state.expanded.reduce((acc, cur) => {
@@ -36,10 +41,6 @@ class RowExpandProvider extends React.Component {
} }
} }
onClosed = (closedRow) => {
this.setState({ isClosing: this.state.isClosing.filter(value => value !== closedRow) });
};
handleRowExpand = (rowKey, expanded, rowIndex, e) => { handleRowExpand = (rowKey, expanded, rowIndex, e) => {
const { data, keyField, expandRow: { onExpand, onlyOneExpanding, nonExpandable } } = this.props; const { data, keyField, expandRow: { onExpand, onlyOneExpanding, nonExpandable } } = this.props;
if (nonExpandable && _.contains(nonExpandable, rowKey)) { if (nonExpandable && _.contains(nonExpandable, rowKey)) {

View File

@@ -1,7 +1,9 @@
/* eslint camelcase: 0 */
/* eslint react/prop-types: 0 */ /* eslint react/prop-types: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import Const from '../const'; import Const from '../const';
import _ from '../utils';
import dataOperator from '../store/operators'; import dataOperator from '../store/operators';
import { getSelectionSummary } from '../store/selection'; import { getSelectionSummary } from '../store/selection';
@@ -19,17 +21,17 @@ class SelectionProvider extends React.Component {
this.selected = props.selectRow.selected || []; this.selected = props.selectRow.selected || [];
} }
componentWillReceiveProps(nextProps) {
if (nextProps.selectRow) {
this.selected = nextProps.selectRow.selected || this.selected;
}
}
// exposed API // exposed API
getSelected() { getSelected() {
return this.selected; return this.selected;
} }
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.selectRow) {
this.selected = nextProps.selectRow.selected || this.selected;
}
}
handleRowSelect = (rowKey, checked, rowIndex, e) => { handleRowSelect = (rowKey, checked, rowIndex, e) => {
const { data, keyField, selectRow: { mode, onSelect } } = this.props; const { data, keyField, selectRow: { mode, onSelect } } = this.props;
const { ROW_SELECT_SINGLE } = Const; const { ROW_SELECT_SINGLE } = Const;
@@ -71,7 +73,7 @@ class SelectionProvider extends React.Component {
if (!isUnSelect) { if (!isUnSelect) {
currSelected = selected.concat(dataOperator.selectableKeys(data, keyField, nonSelectable)); currSelected = selected.concat(dataOperator.selectableKeys(data, keyField, nonSelectable));
} else { } else {
currSelected = selected.filter(s => typeof data.find(d => d[keyField] === s) === 'undefined'); currSelected = selected.filter(s => typeof data.find(d => _.get(d, keyField) === s) === 'undefined');
} }
let result; let result;

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint react/require-default-props: 0 */ /* eslint react/require-default-props: 0 */
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
@@ -19,6 +20,11 @@ export default (
dataField: PropTypes.string.isRequired, dataField: PropTypes.string.isRequired,
order: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]).isRequired order: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]).isRequired
})), })),
sort: PropTypes.shape({
dataField: PropTypes.string,
order: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]),
sortFunc: PropTypes.func
}),
defaultSortDirection: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC]) defaultSortDirection: PropTypes.oneOf([Const.SORT_DESC, Const.SORT_ASC])
} }
@@ -26,19 +32,14 @@ export default (
super(props); super(props);
let sortOrder; let sortOrder;
let sortColumn; let sortColumn;
const { columns, defaultSorted, defaultSortDirection } = props; const { defaultSorted, defaultSortDirection, sort } = props;
if (defaultSorted && defaultSorted.length > 0) { if (defaultSorted && defaultSorted.length > 0) {
const sortField = defaultSorted[0].dataField;
sortOrder = defaultSorted[0].order || defaultSortDirection; sortOrder = defaultSorted[0].order || defaultSortDirection;
const sortColumns = columns.filter(col => col.dataField === sortField); sortColumn = this.initSort(defaultSorted[0].dataField, sortOrder);
if (sortColumns.length > 0) { } else if (sort && sort.dataField && sort.order) {
sortColumn = sortColumns[0]; sortOrder = sort.order;
sortColumn = this.initSort(sort.dataField, sortOrder);
if (sortColumn.onSort) {
sortColumn.onSort(sortField, sortOrder);
}
}
} }
this.state = { sortOrder, sortColumn }; this.state = { sortOrder, sortColumn };
} }
@@ -50,6 +51,30 @@ export default (
} }
} }
UNSAFE_componentWillReceiveProps(nextProps) {
const { sort, columns } = nextProps;
if (sort && sort.dataField && sort.order) {
this.setState({
sortOrder: sort.order,
sortColumn: columns.find(col => col.dataField === sort.dataField)
});
}
}
initSort(sortField, sortOrder) {
let sortColumn;
const { columns } = this.props;
const sortColumns = columns.filter(col => col.dataField === sortField);
if (sortColumns.length > 0) {
sortColumn = sortColumns[0];
if (sortColumn.onSort) {
sortColumn.onSort(sortField, sortOrder);
}
}
return sortColumn;
}
handleSort = (column) => { handleSort = (column) => {
const sortOrder = dataOperator.nextOrder(column, this.state, this.props.defaultSortDirection); const sortOrder = dataOperator.nextOrder(column, this.state, this.props.defaultSortDirection);
@@ -68,9 +93,11 @@ export default (
render() { render() {
let { data } = this.props; let { data } = this.props;
const { sort } = this.props;
const { sortOrder, sortColumn } = this.state; const { sortOrder, sortColumn } = this.state;
if (!isRemoteSort() && sortColumn) { if (!isRemoteSort() && sortColumn) {
data = dataOperator.sort(data, sortOrder, sortColumn); const sortFunc = sortColumn.sortFunc ? sortColumn.sortFunc : (sort && sort.sortFunc);
data = dataOperator.sort(data, sortOrder, { ...sortColumn, sortFunc });
} }
return ( return (

View File

@@ -0,0 +1,49 @@
import React from 'react';
import PropTypes from 'prop-types';
import _ from './utils';
const FiltersCell = (props) => {
const {
index, column, onExternalFilter,
currFilters, onFilter
} = props;
const { filterRenderer, filter } = column;
let filterElm;
const cellAttrs = {};
const cellStyle = {};
cellAttrs.style = cellStyle;
if (column.headerAlign) {
cellStyle.textAlign = _.isFunction(column.headerAlign)
? column.headerAlign(column, index)
: column.headerAlign;
}
if (column.filterRenderer) {
const onCustomFilter = onExternalFilter(column, filter.props.type);
filterElm = filterRenderer(onCustomFilter, column);
} else if (filter) {
filterElm = (
<filter.Filter
{ ...filter.props }
filterState={ currFilters[column.dataField] }
onFilter={ onFilter }
column={ column }
/>
);
}
return React.createElement('th', cellAttrs, filterElm);
};
FiltersCell.propTypes = {
index: PropTypes.number.isRequired,
column: PropTypes.object.isRequired,
currFilters: PropTypes.object.isRequired,
onFilter: PropTypes.func,
onExternalFilter: PropTypes.func
};
FiltersCell.defaultProps = {
onFilter: () => { },
onExternalFilter: () => { }
};
export default FiltersCell;

View File

@@ -0,0 +1,83 @@
/* eslint react/require-default-props: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import FiltersCell from './filters-cell';
import Const from './const';
import RowTemplate from './row/row-template';
const Filters = (props) => {
const {
columns,
onFilter,
currFilters,
filterPosition,
onExternalFilter,
className,
selectRow,
expandRow
} = props;
function renderContent() {
const filterColumns = [];
let showFiltersRow = false;
columns.forEach((column, i) => {
filterColumns.push(<FiltersCell
index={ i }
key={ column.dataField }
column={ column }
currFilters={ currFilters }
onExternalFilter={ onExternalFilter }
onFilter={ onFilter }
/>);
if (column.filterRenderer || column.filter) {
if (!showFiltersRow) {
showFiltersRow = true;
}
}
});
return filterColumns;
}
return (
<tbody
className={ className }
style={ {
display:
filterPosition === Const.FILTERS_POSITION_TOP
? 'table-header-group'
: 'table-footer-group'
} }
>
<RowTemplate
renderContent={ renderContent }
selectRow={ selectRow }
expandRow={ expandRow }
cellEl="td"
/>
</tbody>
);
};
Filters.propTypes = {
columns: PropTypes.array.isRequired,
onFilter: PropTypes.func,
filterPosition: PropTypes.oneOf([
Const.FILTERS_POSITION_TOP,
Const.FILTERS_POSITION_INLINE,
Const.FILTERS_POSITION_BOTTOM
]),
currFilters: PropTypes.object,
onExternalFilter: PropTypes.func,
className: PropTypes.string,
selectRow: PropTypes.object,
expandRow: PropTypes.object
};
Filters.defaultProps = {
position: Const.FILTERS_POSITION_TOP
};
export default Filters;

View File

@@ -4,56 +4,61 @@ import cs from 'classnames';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import _ from './utils'; import _ from './utils';
import eventDelegater from './cell-event-delegater';
const FooterCell = (props) => { class FooterCell extends eventDelegater(React.Component) {
const { index, column, columnData } = props; render() {
const { index, column, columnData } = this.props;
const { const {
footer, footer,
footerTitle, footerTitle,
footerAlign, footerAlign,
footerFormatter, footerFormatter,
footerEvents, footerEvents,
footerClasses, footerClasses,
footerStyle, footerStyle,
footerAttrs footerAttrs
} = column; } = column;
const cellAttrs = { const delegateEvents = this.delegate(footerEvents);
...(_.isFunction(footerAttrs) ? footerAttrs(column, index) : footerAttrs), const cellAttrs = {
...footerEvents ...(_.isFunction(footerAttrs) ? footerAttrs(column, index) : footerAttrs),
}; ...delegateEvents
};
let text = '';
if (_.isString(footer)) { let text = '';
text = footer; if (_.isString(footer)) {
} else if (_.isFunction(footer)) { text = footer;
text = footer(columnData, column, index); } else if (_.isFunction(footer)) {
text = footer(columnData, column, index);
}
let cellStyle = {};
const cellClasses = _.isFunction(footerClasses) ? footerClasses(column, index) : footerClasses;
if (footerStyle) {
cellStyle = _.isFunction(footerStyle) ? footerStyle(column, index) : footerStyle;
cellStyle = cellStyle ? { ...cellStyle } : cellStyle;
}
if (footerTitle) {
cellAttrs.title = _.isFunction(footerTitle) ? footerTitle(column, index) : text;
}
if (footerAlign) {
cellStyle.textAlign = _.isFunction(footerAlign) ? footerAlign(column, index) : footerAlign;
}
if (cellClasses) cellAttrs.className = cs(cellAttrs.className, cellClasses);
if (!_.isEmptyObject(cellStyle)) cellAttrs.style = cellStyle;
const children = footerFormatter ? footerFormatter(column, index) : text;
return React.createElement('th', cellAttrs, children);
} }
}
let cellStyle = {};
const cellClasses = _.isFunction(footerClasses) ? footerClasses(column, index) : footerClasses;
if (footerStyle) {
cellStyle = _.isFunction(footerStyle) ? footerStyle(column, index) : footerStyle;
cellStyle = cellStyle ? { ...cellStyle } : cellStyle;
}
if (footerTitle) {
cellAttrs.title = _.isFunction(footerTitle) ? footerTitle(column, index) : text;
}
if (footerAlign) {
cellStyle.textAlign = _.isFunction(footerAlign) ? footerAlign(column, index) : footerAlign;
}
if (cellClasses) cellAttrs.className = cs(cellAttrs.className, cellClasses);
if (!_.isEmptyObject(cellStyle)) cellAttrs.style = cellStyle;
const children = footerFormatter ? footerFormatter(column, index) : text;
return React.createElement('th', cellAttrs, children);
};
FooterCell.propTypes = { FooterCell.propTypes = {
columnData: PropTypes.array, columnData: PropTypes.array,

View File

@@ -2,57 +2,41 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import Const from './const'; import RowTemplate from './row/row-template';
import FooterCell from './footer-cell'; import FooterCell from './footer-cell';
import _ from './utils'; import _ from './utils';
const Footer = (props) => { const Footer = (props) => {
const { data, className, columns, selectRow, expandRow } = props; const { data, className, columns, selectRow, expandRow } = props;
const SelectionFooterCellComp = () => <th />;
const ExpansionFooterCellComp = () => <th />;
const isRenderFunctionColumnInLeft = ( function renderContent() {
position = Const.INDICATOR_POSITION_LEFT return columns.map((column, i) => {
) => position === Const.INDICATOR_POSITION_LEFT; if (column.footer === undefined || column.footer === null) {
return false;
}
const childrens = columns.map((column, i) => { const columnData = _.pluck(data, column.dataField);
if (column.footer === undefined || column.footer === null) {
return false;
}
const columnData = _.pluck(data, column.dataField); return (
<FooterCell
return ( index={ i }
<FooterCell key={ column.dataField }
index={ i } column={ column }
key={ column.dataField } columnData={ columnData }
column={ column } />
columnData={ columnData } );
/> });
);
});
if (selectRow && selectRow.hideSelectColumn !== true) {
if (isRenderFunctionColumnInLeft(selectRow.selectColumnPosition)) {
childrens.unshift(<SelectionFooterCellComp key="selection" />);
} else {
childrens.push(<SelectionFooterCellComp key="selection" />);
}
}
if (expandRow.showExpandColumn) {
if (isRenderFunctionColumnInLeft(expandRow.expandColumnPosition)) {
childrens.unshift(<ExpansionFooterCellComp key="expansion" />);
} else {
childrens.push(<ExpansionFooterCellComp key="expansion" />);
}
} }
return ( return (
<tfoot> <tfoot>
<tr className={ className }> <RowTemplate
{ childrens } renderContent={ renderContent }
</tr> selectRow={ selectRow }
expandRow={ expandRow }
className={ className }
cellEl="th"
/>
</tfoot> </tfoot>
); );
}; };

View File

@@ -7,119 +7,136 @@ import Const from './const';
import SortSymbol from './sort/symbol'; import SortSymbol from './sort/symbol';
import SortCaret from './sort/caret'; import SortCaret from './sort/caret';
import _ from './utils'; import _ from './utils';
import eventDelegater from './cell-event-delegater';
const HeaderCell = (props) => { class HeaderCell extends eventDelegater(React.Component) {
const { render() {
column, const {
index, column,
onSort, index,
sorting, onSort,
sortOrder, sorting,
isLastSorting, sortOrder,
onFilter, isLastSorting,
currFilters, onFilter,
onExternalFilter currFilters,
} = props; filterPosition,
onExternalFilter,
globalSortCaret
} = this.props;
const { const {
text, text,
sort, sort,
sortCaret, sortCaret,
filter, filter,
filterRenderer, filterRenderer,
headerTitle, headerTitle,
headerAlign, headerAlign,
headerFormatter, headerFormatter,
headerEvents, headerEvents,
headerClasses, headerClasses,
headerStyle, headerStyle,
headerAttrs, headerAttrs,
headerSortingClasses, headerSortingClasses,
headerSortingStyle headerSortingStyle
} = column; } = column;
const cellAttrs = { const sortCaretfunc = sortCaret || globalSortCaret;
..._.isFunction(headerAttrs) ? headerAttrs(column, index) : headerAttrs,
...headerEvents,
tabIndex: 0
};
let sortSymbol; const delegateEvents = this.delegate(headerEvents);
let filterElm;
let cellStyle = {};
let cellClasses = _.isFunction(headerClasses) ? headerClasses(column, index) : headerClasses;
if (headerStyle) { const customAttrs = _.isFunction(headerAttrs)
cellStyle = _.isFunction(headerStyle) ? headerStyle(column, index) : headerStyle; ? headerAttrs(column, index)
cellStyle = cellStyle ? { ...cellStyle } : cellStyle; : (headerAttrs || {});
}
if (headerTitle) { const cellAttrs = {
cellAttrs.title = _.isFunction(headerTitle) ? headerTitle(column, index) : text; ...customAttrs,
} ...delegateEvents,
tabIndex: _.isDefined(customAttrs.tabIndex) ? customAttrs.tabIndex : 0
if (headerAlign) {
cellStyle.textAlign = _.isFunction(headerAlign) ? headerAlign(column, index) : headerAlign;
}
if (sort) {
const customClick = cellAttrs.onClick;
cellAttrs.onClick = (e) => {
onSort(column);
if (_.isFunction(customClick)) customClick(e);
}; };
cellAttrs.className = cs(cellAttrs.className, 'sortable');
if (sorting) { let sortSymbol;
sortSymbol = sortCaret ? sortCaret(sortOrder, column) : <SortCaret order={ sortOrder } />; let filterElm;
let cellStyle = {};
let cellClasses = _.isFunction(headerClasses) ? headerClasses(column, index) : headerClasses;
// append customized classes or style if table was sorting based on the current column. if (headerStyle) {
cellClasses = cs( cellStyle = _.isFunction(headerStyle) ? headerStyle(column, index) : headerStyle;
cellClasses, cellStyle = cellStyle ? { ...cellStyle } : cellStyle;
_.isFunction(headerSortingClasses)
? headerSortingClasses(column, sortOrder, isLastSorting, index)
: headerSortingClasses
);
cellStyle = {
...cellStyle,
..._.isFunction(headerSortingStyle)
? headerSortingStyle(column, sortOrder, isLastSorting, index)
: headerSortingStyle
};
} else {
sortSymbol = sortCaret ? sortCaret(undefined, column) : <SortSymbol />;
} }
if (headerTitle) {
cellAttrs.title = _.isFunction(headerTitle) ? headerTitle(column, index) : text;
}
if (headerAlign) {
cellStyle.textAlign = _.isFunction(headerAlign) ? headerAlign(column, index) : headerAlign;
}
if (sort) {
const customClick = cellAttrs.onClick;
cellAttrs.onClick = (e) => {
onSort(column);
if (_.isFunction(customClick)) customClick(e);
};
cellAttrs.className = cs(cellAttrs.className, 'sortable');
if (sorting) {
sortSymbol = sortCaretfunc ?
sortCaretfunc(sortOrder, column) :
<SortCaret order={ sortOrder } />;
// append customized classes or style if table was sorting based on the current column.
cellClasses = cs(
cellClasses,
_.isFunction(headerSortingClasses)
? headerSortingClasses(column, sortOrder, isLastSorting, index)
: headerSortingClasses
);
cellStyle = {
...cellStyle,
..._.isFunction(headerSortingStyle)
? headerSortingStyle(column, sortOrder, isLastSorting, index)
: headerSortingStyle
};
} else {
sortSymbol = sortCaretfunc ? sortCaretfunc(undefined, column) : <SortSymbol />;
}
}
if (cellClasses) cellAttrs.className = cs(cellAttrs.className, cellClasses);
if (!_.isEmptyObject(cellStyle)) cellAttrs.style = cellStyle;
if (filterPosition === Const.FILTERS_POSITION_INLINE) {
if (filterRenderer) {
const onCustomFilter = onExternalFilter(column, filter.props.type);
filterElm = filterRenderer(onCustomFilter, column);
} else if (filter) {
filterElm = (
<filter.Filter
{ ...filter.props }
filterState={ currFilters[column.dataField] }
onFilter={ onFilter }
column={ column }
/>
);
}
}
const children = headerFormatter ?
headerFormatter(column, index, { sortElement: sortSymbol, filterElement: filterElm }) :
text;
if (headerFormatter) {
return React.createElement('th', cellAttrs, children);
}
return React.createElement('th', cellAttrs, children, sortSymbol, filterElm);
} }
}
if (cellClasses) cellAttrs.className = cs(cellAttrs.className, cellClasses);
if (!_.isEmptyObject(cellStyle)) cellAttrs.style = cellStyle;
if (filterRenderer) {
const onCustomFilter = onExternalFilter(column, filter.props.type);
filterElm = filterRenderer(onCustomFilter, column);
} else if (filter) {
filterElm = (
<filter.Filter
{ ...filter.props }
filterState={ currFilters[column.dataField] }
onFilter={ onFilter }
column={ column }
/>
);
}
const children = headerFormatter ?
headerFormatter(column, index, { sortElement: sortSymbol, filterElement: filterElm }) :
text;
if (headerFormatter) {
return React.createElement('th', cellAttrs, children);
}
return React.createElement('th', cellAttrs, children, sortSymbol, filterElm);
};
HeaderCell.propTypes = { HeaderCell.propTypes = {
column: PropTypes.shape({ column: PropTypes.shape({
@@ -171,6 +188,8 @@ HeaderCell.propTypes = {
sortCaret: PropTypes.func, sortCaret: PropTypes.func,
isLastSorting: PropTypes.bool, isLastSorting: PropTypes.bool,
onFilter: PropTypes.func, onFilter: PropTypes.func,
filterPosition: PropTypes.oneOf([Const.FILTERS_POSITION_INLINE,
Const.FILTERS_POSITION_BOTTOM, Const.FILTERS_POSITION_TOP]),
currFilters: PropTypes.object, currFilters: PropTypes.object,
onExternalFilter: PropTypes.func onExternalFilter: PropTypes.func
}; };

View File

@@ -18,9 +18,11 @@ const Header = (props) => {
sortField, sortField,
sortOrder, sortOrder,
selectRow, selectRow,
expandRow,
currFilters, currFilters,
onExternalFilter, onExternalFilter,
expandRow filterPosition,
globalSortCaret
} = props; } = props;
let SelectionHeaderCellComp = () => null; let SelectionHeaderCellComp = () => null;
@@ -50,11 +52,13 @@ const Header = (props) => {
column={ column } column={ column }
onSort={ onSort } onSort={ onSort }
sorting={ currSort } sorting={ currSort }
sortOrder={ sortOrder }
globalSortCaret={ globalSortCaret }
isLastSorting={ isLastSorting }
onFilter={ onFilter } onFilter={ onFilter }
currFilters={ currFilters } currFilters={ currFilters }
onExternalFilter={ onExternalFilter } onExternalFilter={ onExternalFilter }
sortOrder={ sortOrder } filterPosition={ filterPosition }
isLastSorting={ isLastSorting }
/>); />);
}) })
]; ];
@@ -93,8 +97,14 @@ Header.propTypes = {
selectRow: PropTypes.object, selectRow: PropTypes.object,
currFilters: PropTypes.object, currFilters: PropTypes.object,
onExternalFilter: PropTypes.func, onExternalFilter: PropTypes.func,
globalSortCaret: PropTypes.func,
className: PropTypes.string, className: PropTypes.string,
expandRow: PropTypes.object expandRow: PropTypes.object,
filterPosition: PropTypes.oneOf([
Const.FILTERS_POSITION_TOP,
Const.FILTERS_POSITION_INLINE,
Const.FILTERS_POSITION_BOTTOM
])
}; };
export default Header; export default Header;

View File

@@ -1,7 +1,13 @@
export default ExtendBase => export default ExtendBase =>
class ColumnResolver extends ExtendBase { class ColumnResolver extends ExtendBase {
visibleColumnSize(includeSelectColumn = true) { visibleColumnSize(includeSelectColumn = true) {
let columnLen = this.props.columns.filter(c => !c.hidden).length; let columnLen;
if (this.props.columnToggle && this.props.columnToggle.toggles) {
const columns = this.props.columnToggle.toggles;
columnLen = Object.keys(columns).filter(name => columns[name]).length;
} else {
columnLen = this.props.columns.filter(c => !c.hidden).length;
}
if (!includeSelectColumn) return columnLen; if (!includeSelectColumn) return columnLen;
if (this.props.selectRow && !this.props.selectRow.hideSelectColumn) { if (this.props.selectRow && !this.props.selectRow.hideSelectColumn) {
columnLen += 1; columnLen += 1;

View File

@@ -44,7 +44,7 @@ export default class ExpandCell extends Component {
if (tabIndex !== -1) attrs.tabIndex = tabIndex; if (tabIndex !== -1) attrs.tabIndex = tabIndex;
return ( return (
<td onClick={ this.handleClick } { ...attrs }> <td className="expand-cell" onClick={ this.handleClick } { ...attrs }>
{ {
expandColumnRenderer ? expandColumnRenderer({ expandColumnRenderer ? expandColumnRenderer({
expandable, expandable,

View File

@@ -28,7 +28,7 @@ export default class ExpansionHeaderCell extends Component {
}; };
return ( return (
<th data-row-selection { ...attrs }> <th className="expand-cell-header" data-row-selection { ...attrs }>
{ {
expandHeaderColumnRenderer ? expandHeaderColumnRenderer ?
expandHeaderColumnRenderer({ isAnyExpands }) : expandHeaderColumnRenderer({ isAnyExpands }) :

View File

@@ -9,6 +9,7 @@ export default (Component) => {
const key = props.value; const key = props.value;
const selected = _.contains(selectRow.selected, key); const selected = _.contains(selectRow.selected, key);
const selectable = !selectRow.nonSelectable || !_.contains(selectRow.nonSelectable, key); const selectable = !selectRow.nonSelectable || !_.contains(selectRow.nonSelectable, key);
const notSelectable = _.contains(selectRow.nonSelectable, key);
let { let {
style, style,
@@ -38,6 +39,22 @@ export default (Component) => {
} }
} }
if (notSelectable) {
const notSelectableStyle = _.isFunction(selectRow.nonSelectableStyle)
? selectRow.nonSelectableStyle(props.row, props.rowIndex)
: selectRow.nonSelectableStyle;
const notSelectableClasses = _.isFunction(selectRow.nonSelectableClasses)
? selectRow.nonSelectableClasses(props.row, props.rowIndex)
: selectRow.nonSelectableClasses;
style = {
...style,
...notSelectableStyle
};
className = cs(className, notSelectableClasses) || undefined;
}
return ( return (
<Component <Component
{ ...props } { ...props }

View File

@@ -86,7 +86,7 @@ export default class SelectionCell extends Component {
<BootstrapContext.Consumer> <BootstrapContext.Consumer>
{ {
({ bootstrap4 }) => ( ({ bootstrap4 }) => (
<td onClick={ this.handleClick } { ...attrs }> <td className="selection-cell" onClick={ this.handleClick } { ...attrs }>
{ {
selectionRenderer ? selectionRenderer({ selectionRenderer ? selectionRenderer({
mode: inputType, mode: inputType,

View File

@@ -112,7 +112,7 @@ export default class SelectionHeaderCell extends Component {
); );
} }
return ( return (
<th data-row-selection { ...attrs }>{ content }</th> <th className="selection-cell-header" data-row-selection { ...attrs }>{ content }</th>
); );
} }
} }

View File

@@ -0,0 +1,48 @@
/* eslint react/require-default-props: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import Const from '../const';
const RowTemplate = (props) => {
const {
renderContent,
selectRow,
expandRow,
cellEl,
...rest
} = props;
const isRenderFunctionColumnInLeft = (
position = Const.INDICATOR_POSITION_LEFT
) => position === Const.INDICATOR_POSITION_LEFT;
const childrens = renderContent() || [];
if (selectRow && selectRow.hideSelectColumn !== true) {
if (isRenderFunctionColumnInLeft(selectRow.selectColumnPosition)) {
childrens.unshift(React.createElement(cellEl, { key: 'selection' }));
} else {
childrens.push(React.createElement(cellEl, { key: 'selection' }));
}
}
if (expandRow.showExpandColumn) {
if (isRenderFunctionColumnInLeft(expandRow.expandColumnPosition)) {
childrens.unshift(React.createElement(cellEl, { key: 'expansion' }));
} else {
childrens.push(React.createElement(cellEl, { key: 'expansion' }));
}
}
return <tr { ...rest }>{ childrens }</tr>;
};
RowTemplate.propTypes = {
renderContent: PropTypes.func.isRequired,
cellEl: PropTypes.string.isRequired,
selectRow: PropTypes.object,
expandRow: PropTypes.object
};
export default RowTemplate;

View File

@@ -2,14 +2,14 @@ import _ from '../utils';
import { getRowByRowId } from './rows'; import { getRowByRowId } from './rows';
export const getSelectionSummary = ( export const getSelectionSummary = (
data, data = [],
keyField, keyField,
selected = [] selected = []
) => { ) => {
let allRowsSelected = data.length > 0; let allRowsSelected = data.length > 0;
let allRowsNotSelected = true; let allRowsNotSelected = true;
const rowKeys = data.map(d => d[keyField]); const rowKeys = data.map(d => _.get(d, keyField));
for (let i = 0; i < rowKeys.length; i += 1) { for (let i = 0; i < rowKeys.length; i += 1) {
const curr = rowKeys[i]; const curr = rowKeys[i];
if (typeof selected.find(x => x === curr) === 'undefined') { if (typeof selected.find(x => x === curr) === 'undefined') {
@@ -24,7 +24,7 @@ export const getSelectionSummary = (
}; };
}; };
export const selectableKeys = (data, keyField, skips = []) => { export const selectableKeys = (data = [], keyField, skips = []) => {
if (skips.length === 0) { if (skips.length === 0) {
return data.map(row => _.get(row, keyField)); return data.map(row => _.get(row, keyField));
} }
@@ -40,6 +40,6 @@ export const unSelectableKeys = (selected, skips = []) => {
return selected.filter(x => _.contains(skips, x)); return selected.filter(x => _.contains(skips, x));
}; };
export const getSelectedRows = (data, keyField, selected) => export const getSelectedRows = (data = [], keyField, selected) =>
selected.map(k => getRowByRowId(data, keyField, k)).filter(x => !!x); selected.map(k => getRowByRowId(data, keyField, k)).filter(x => !!x);

View File

@@ -14,14 +14,19 @@ function comparator(a, b) {
return result; return result;
} }
export const sort = (data, sortOrder, { dataField, sortFunc }) => { export const sort = (data, sortOrder, { dataField, sortFunc, sortValue }) => {
const _data = [...data]; const _data = [...data];
_data.sort((a, b) => { _data.sort((a, b) => {
let result; let result;
let valueA = _.get(a, dataField); let valueA = _.get(a, dataField);
let valueB = _.get(b, dataField); let valueB = _.get(b, dataField);
valueA = _.isDefined(valueA) ? valueA : ''; if (sortValue) {
valueB = _.isDefined(valueB) ? valueB : ''; valueA = sortValue(valueA, a);
valueB = sortValue(valueB, b);
} else {
valueA = _.isDefined(valueA) ? valueA : '';
valueB = _.isDefined(valueB) ? valueB : '';
}
if (sortFunc) { if (sortFunc) {
result = sortFunc(valueA, valueB, sortOrder, dataField, a, b); result = sortFunc(valueA, valueB, sortOrder, dataField, a, b);

View File

@@ -81,7 +81,7 @@ describe('DataContext', () => {
beforeEach(() => { beforeEach(() => {
wrapper = shallow(shallowContext()); wrapper = shallow(shallowContext());
wrapper.instance().componentWillReceiveProps({ wrapper.instance().UNSAFE_componentWillReceiveProps({
data: newData data: newData
}); });
}); });

View File

@@ -99,7 +99,7 @@ describe('DataContext', () => {
beforeEach(() => { beforeEach(() => {
wrapper = shallow(shallowContext()); wrapper = shallow(shallowContext());
wrapper.instance().componentWillReceiveProps({ wrapper.instance().UNSAFE_componentWillReceiveProps({
selectRow: newSelectRow selectRow: newSelectRow
}); });
}); });
@@ -115,7 +115,7 @@ describe('DataContext', () => {
...defaultSelectRow, ...defaultSelectRow,
selected: defaultSelected selected: defaultSelected
})); }));
wrapper.instance().componentWillReceiveProps({ wrapper.instance().UNSAFE_componentWillReceiveProps({
selectRow: defaultSelectRow selectRow: defaultSelectRow
}); });
}); });
@@ -128,7 +128,7 @@ describe('DataContext', () => {
describe('if nextProps.selectRow is not existing', () => { describe('if nextProps.selectRow is not existing', () => {
beforeEach(() => { beforeEach(() => {
wrapper = shallow(shallowContext()); wrapper = shallow(shallowContext());
wrapper.instance().componentWillReceiveProps({}); wrapper.instance().UNSAFE_componentWillReceiveProps({});
}); });
it('should not set this.selected', () => { it('should not set this.selected', () => {

View File

@@ -48,7 +48,7 @@ describe('Footer', () => {
describe('simplest footer', () => { describe('simplest footer', () => {
beforeEach(() => { beforeEach(() => {
wrapper = shallow( wrapper = render(
<Footer <Footer
data={ data } data={ data }
columns={ columns } columns={ columns }
@@ -61,7 +61,7 @@ describe('Footer', () => {
it('should render successfully', () => { it('should render successfully', () => {
expect(wrapper.length).toBe(1); expect(wrapper.length).toBe(1);
expect(wrapper.find('tr').length).toBe(1); expect(wrapper.find('tr').length).toBe(1);
expect(wrapper.find(FooterCell).length).toBe(columns.length); expect(wrapper.find('th').length).toBe(columns.length);
}); });
}); });
@@ -86,7 +86,7 @@ describe('Footer', () => {
}); });
}); });
describe('when selecrRow prop is enable', () => { describe('when selectRow prop is enable', () => {
beforeEach(() => { beforeEach(() => {
wrapper = render( wrapper = render(
<Footer <Footer

View File

@@ -729,7 +729,13 @@ describe('HeaderCell', () => {
} }
}; };
wrapper = shallow( wrapper = shallow(
<HeaderCell column={ column } index={ index } onFilter={ onFilter } currFilters={ {} } /> <HeaderCell
column={ column }
index={ index }
onFilter={ onFilter }
currFilters={ {} }
filterPosition="inline"
/>
); );
}); });
@@ -767,7 +773,12 @@ describe('HeaderCell', () => {
filterRenderer filterRenderer
}; };
wrapper = shallow( wrapper = shallow(
<HeaderCell column={ column } index={ index } onExternalFilter={ onExternalFilter } />); <HeaderCell
column={ column }
index={ index }
filterPosition="inline"
onExternalFilter={ onExternalFilter }
/>);
}); });
it('should render successfully', () => { it('should render successfully', () => {

View File

@@ -2,6 +2,7 @@
exports[`<SelectionCell /> render should render component correctly 1`] = ` exports[`<SelectionCell /> render should render component correctly 1`] = `
<td <td
className="selection-cell"
onClick={[Function]} onClick={[Function]}
> >
<input <input

View File

@@ -1686,9 +1686,10 @@ class-utils@^0.3.5:
isobject "^3.0.0" isobject "^3.0.0"
static-extend "^0.1.1" static-extend "^0.1.1"
classnames@2.2.5: classnames@^2.2.5:
version "2.2.5" version "2.2.6"
resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.2.5.tgz#fb3801d453467649ef3603c7d61a02bd129bde6d" resolved "https://registry.yarnpkg.com/classnames/-/classnames-2.2.6.tgz#43935bffdd291f326dad0a205309b38d00f650ce"
integrity sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q==
clean-css@4.1.9, clean-css@4.1.x: clean-css@4.1.9, clean-css@4.1.x:
version "4.1.9" version "4.1.9"