Compare commits

..

83 Commits

Author SHA1 Message Date
AllenFang
4daa5ef4d7 Publish
- react-bootstrap-table2-example@1.0.34
 - react-bootstrap-table-next@3.3.1
2019-11-16 14:59:15 +08:00
Allen
acb9c9f61e Merge pull request #1166 from react-bootstrap-table/develop
20191116 release
2019-11-16 14:56:01 +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
5a44384e3c Publish
- react-bootstrap-table2-example@1.0.33
 - react-bootstrap-table2-filter@1.3.0
 - react-bootstrap-table-next@3.3.0
2019-11-09 15:03:03 +08:00
Allen
ec742a43f6 Merge pull request #1149 from react-bootstrap-table/develop
20191109 release
2019-11-09 15:01:06 +08: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
be916d81a3 Publish
- react-bootstrap-table2-example@1.0.32
 - react-bootstrap-table-next@3.2.1
2019-09-30 13:04:37 +08:00
Allen
49d1ce8812 Merge pull request #1109 from react-bootstrap-table/develop
20190929 release
2019-09-30 13:01:54 +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
cf5b24e9e8 Publish
- react-bootstrap-table2-editor@1.4.0
 - react-bootstrap-table2-example@1.0.31
 - react-bootstrap-table2-filter@1.2.0
 - react-bootstrap-table2-paginator@2.1.0
 - react-bootstrap-table2-toolkit@2.1.0
 - react-bootstrap-table-next@3.2.0
2019-09-08 15:31:51 +08:00
Allen
da86b4aa1a Merge pull request #1087 from react-bootstrap-table/develop
20190908 release
2019-09-08 15:30:23 +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
AllenFang
bb42514e56 Publish
- react-bootstrap-table2-example@1.0.30
 - react-bootstrap-table2-filter@1.1.12
 - react-bootstrap-table-next@3.1.9
2019-08-25 21:56:08 +08:00
Allen
79e3247921 Merge pull request #1070 from react-bootstrap-table/develop
20190825 release
2019-08-25 21:54:57 +08:00
AllenFang
c25192145f docs for #1006 2019-08-24 14:59:58 +08:00
AllenFang
056957b0b5 add story for #1006 2019-08-24 14:59:49 +08:00
AllenFang
c12d3faba3 fix #1006 2019-08-24 14:59:36 +08:00
AllenFang
963b8d669b add story and docs for #1067 2019-08-24 14:04:49 +08:00
AllenFang
47f6340a99 story for #1054 2019-08-24 13:22:14 +08:00
AllenFang
23cb0bb317 fix #1054 2019-08-24 13:22:04 +08:00
AllenFang
70827eecd6 fix #1061 2019-08-19 21:28:22 +08:00
AllenFang
43b5eeb74f fix #1062 2019-08-19 21:17:00 +08:00
AllenFang
eb204f6526 fix #1060 2019-08-18 17:04:17 +08:00
Bill Parrott
2b410fb8ac Merge branch 'master' of github.com:react-bootstrap-table/react-bootstrap-table2 2019-08-12 13:34:14 -05:00
AllenFang
110744f4cb Publish
- react-bootstrap-table2-editor@1.3.2
 - react-bootstrap-table2-example@1.0.29
 - react-bootstrap-table2-filter@1.1.11
 - react-bootstrap-table2-paginator@2.0.8
 - react-bootstrap-table-next@3.1.8
2019-08-12 21:07:14 +08:00
Allen
47848e7f34 Merge pull request #1053 from react-bootstrap-table/develop
20190810 release
2019-08-12 21:05:44 +08:00
AllenFang
1a44ce0ea6 fix #1051 2019-08-10 15:05:53 +08:00
AllenFang
08ec8a9f65 fix #1044 2019-08-10 14:51:26 +08:00
Allen
27387c2a69 Merge pull request #1052 from react-bootstrap-table/bugfix/column-toggle-with-filter
fix #1030
2019-08-10 14:48:24 +08:00
Dave Carlson
05b50ac71a Update README.md (#1047) 2019-08-10 14:38:59 +08:00
AllenFang
9b6d9904e7 fix test cases for #1030 2019-08-10 14:37:40 +08:00
AllenFang
4de565b759 fix #1030 2019-08-10 14:37:13 +08:00
Peperoncino
c53d2612d4 Fromatted Value => Formatted Value (#1038) 2019-08-03 15:49:54 +08:00
Mickaël Gauvin
0c2863d63c Update multiselect.js (#1025)
applyFilter should take the entire selection and not just the first element of the sélection
2019-08-03 15:49:09 +08:00
AllenFang
a534d525c9 fix wrong example code 2019-07-27 17:11:59 +08:00
AllenFang
856e63d524 fix #1027 2019-07-27 17:11:11 +08:00
Allen
c59b963436 Update issue templates 2019-07-27 16:43:54 +08:00
Allen
b50dc95e06 Update issue templates 2019-07-27 16:41:44 +08:00
Allen
2619a1e424 Update issue templates 2019-07-27 16:37:09 +08:00
Allen
423769c134 fix #1007 (#1032) 2019-07-27 16:19:52 +08:00
AllenFang
6530ff1570 Publish
- react-bootstrap-table-next@3.1.7
2019-07-22 20:22:38 +08:00
AllenFang
9af61b54b1 Publish
- react-bootstrap-table2-editor@1.3.1
2019-07-22 20:22:09 +08:00
AllenFang
72f7333a34 Publish
- react-bootstrap-table2-editor@1.3.0
 - react-bootstrap-table2-example@1.0.28
 - react-bootstrap-table-next@3.1.6
2019-07-22 20:14:49 +08:00
Allen
64c113da26 Merge pull request #1023 from react-bootstrap-table/develop
20190721 release
2019-07-22 20:08:57 +08:00
AllenFang
db22bb9adb fix #1015 2019-07-21 16:52:28 +08:00
AllenFang
d7e1f1dfd0 fix #1014 2019-07-21 16:45:11 +08:00
AllenFang
c277c8139e fix #1007 2019-07-21 16:07:26 +08:00
AllenFang
ec4864da5c fix #993 2019-07-13 16:28:48 +08:00
AllenFang
92f1449177 fix #1004 2019-07-13 15:28:12 +08:00
Gena M
46258b0264 Update README, overlayFactory example (#997)
Update example of usage `overlayFactory` according to "react-loading-overlay" documentation.
2019-07-13 13:57:03 +08:00
AllenFang
5e8bb3426a Publish
- react-bootstrap-table2-example@1.0.27
 - react-bootstrap-table2-filter@1.1.10
 - react-bootstrap-table2-paginator@2.0.7
 - react-bootstrap-table-next@3.1.5
2019-06-25 23:13:31 +08:00
Allen
03f2ce4792 Merge pull request #991 from react-bootstrap-table/develop
20190625 release
2019-06-25 23:12:05 +08:00
AllenFang
7382010822 fix #970 2019-06-22 15:47:21 +08:00
Allen
a1a59f9419 fix #980 (#987) 2019-06-22 15:24:28 +08:00
Allen
59f184d74d fix #971 (#986) 2019-06-22 14:45:53 +08:00
Allen
643b9bca5f Merge pull request #985 from react-bootstrap-table/bugfix/979
Fix #979
2019-06-22 13:56:29 +08:00
AllenFang
31724fec7f add story for #979 2019-06-22 13:51:04 +08:00
AllenFang
4cf6e65abc fix #979 2019-06-22 13:50:50 +08:00
Bill Parrott
e31b5eb691 set tabindex to 0 for table headers; fixes #955 2019-06-03 09:26:15 -05:00
104 changed files with 2488 additions and 456 deletions

24
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,24 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: AllenFang
---
**Describe the bug**
A clear and concise description of what the bug is. In addition, please search issues before you open a report to make sure there's no any duplicated report
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Screenshots**
If applicable, add screenshots to help explain your problem.
**codesandbox**
Please give a simple and minimal example on https://codesandbox.io so that we can reproduce it easily and handle it effectively

View File

@@ -0,0 +1,23 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: AllenFang
---
**Is this feature requested before?**
Please search issues to make sure to create feature which is never report yet.
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -0,0 +1,17 @@
---
name: I have a question
about: I have a question
title: ''
labels: ''
assignees: AllenFang
---
**Question**
A clear and concise description of you question. In addition, please search issues before you open a question to make sure there's no any duplicated questions.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**codesandbox**
Please give a simple and minimal example on https://codesandbox.io so that we can reproduce it easily.

View File

@@ -1,7 +1,7 @@
# react-bootstrap-table2
[![Build Status](https://travis-ci.org/react-bootstrap-table/react-bootstrap-table2.svg?branch=master)](https://travis-ci.org/react-bootstrap-table/react-bootstrap-table2)
Rebuilt of [react-bootstrap-table](https://github.com/AllenFang/react-bootstrap-table)
Rebuild of [react-bootstrap-table](https://github.com/AllenFang/react-bootstrap-table)
> Note that `react-bootstrap-table2`'s npm module name is [**`react-bootstrap-table-next`**](https://www.npmjs.com/package/react-bootstrap-table-next) due to the name being already taken.

View File

@@ -32,6 +32,7 @@
* [defaultSortDirection](#defaultSortDirection)
* [pagination](#pagination)
* [filter](#filter)
* [filterPosition](filterPosition)
* [onTableChange](#onTableChange)
* [onDataSizeChange](#onDataSizeChange)
@@ -98,7 +99,14 @@ import overlayFactory from 'react-bootstrap-table2-overlay';
Actually, `react-bootstrap-table-overlay` is depends on [`react-loading-overlay`](https://github.com/derrickpelletier/react-loading-overlay) and `overlayFactory` just a factory function and you can pass any props which available for `react-loading-overlay`:
```js
overlay={ overlayFactory({ spinner: true, background: 'rgba(192,192,192,0.3)' }) }
overlay={
overlayFactory({
spinner: true,
styles: {
overlay: (base) => ({...base, background: 'rgba(255, 0, 0, 0.5)'})
}
})
}
```
### <a name='caption'>caption - [String | Node]</a>
@@ -201,6 +209,8 @@ const defaultSorted = [{
}];
```
**Note**: Only the first column is sorted currently, see #1083.
### <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`.
@@ -320,6 +330,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>
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

@@ -11,7 +11,9 @@ Available properties in a column object:
* [hidden](#hidden)
* [formatter](#formatter)
* [formatExtraData](#formatExtraData)
* [type](#type)
* [sort](#sort)
* [sortValue](#sortValue)
* [sortFunc](#sortFunc)
* [sortCaret](#sortCaret)
* [onSort](#onSort)
@@ -48,6 +50,7 @@ Available properties in a column object:
* [editorRenderer](#editorRenderer)
* [filter](#filter)
* [filterValue](#filterValue)
* [searchable](#searchable)
* [csvType](#csvType)
* [csvFormatter](#csvFormatter)
* [csvText](#csvText)
@@ -132,11 +135,49 @@ The third argument: `components` have following specified properties:
## <a name='formatExtraData'>column.formatExtraData - [Any]</a>
It's only used for [`column.formatter`](#formatter), you can define any value for it and will be passed as fourth argument for [`column.formatter`](#formatter) callback function.
## <a name='type'>column.type - [String]</a>
Specify the data type on column. Available value so far is `string`, `number`, `bool` and `date`. Default is `string`.
`column.type` can be used when you enable the cell editing and want to save your cell data with correct data type.
## <a name='sort'>column.sort - [Bool]</a>
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>
`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
{
@@ -415,7 +456,7 @@ If the events is not listed above, the callback function will only pass the `eve
{
// omit...
headerEvents: {
onClick: e => { ... }
onClick: (e, column, columnIndex) => { ... }
}
}
```
@@ -625,7 +666,7 @@ It's also available to custom via a callback function:
{
// omit...
footerEvents: {
onClick: e => { ... }
onClick: (e, column, columnIndex) => { ... }
}
}
```
@@ -912,6 +953,9 @@ A final `String` value you want to be filtered.
}
```
## <a name='searchable'>column.searchable - [Boolean]</a>
Default the column is searchable. Give `false` to disable search functionality on specified column.
## <a name='csvType'>column.csvType - [Object]</a>
Default is `String`. Currently, the available value is `String` and `Number`. If `Number` assigned, the cell value will not wrapped with double quote.

View File

@@ -18,6 +18,8 @@
* [expandColumnPosition](#expandColumnPosition)
* [expandColumnRenderer](#expandColumnRenderer)
* [expandHeaderColumnRenderer](#expandHeaderColumnRenderer)
* [className](#className)
* [parentClassName](#parentClassName)
### <a name="renderer">expandRow.renderer - [Function]</a>
@@ -25,12 +27,13 @@ Specify the content of expand row, `react-bootstrap-table2` will pass a row obje
#### values
* **row**
* **rowIndex**
#### examples
```js
const expandRow = {
renderer: row => (
renderer: (row, rowIndex) => (
<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>
@@ -165,3 +168,45 @@ const expandRow = {
expandColumnPosition: 'right'
};
```
### <a name='className'>expandRow.className - [String | Function]</a>
Apply the custom class name on the expanding row. For example:
```js
const expandRow = {
renderer: (row) => ...,
className: 'foo'
};
```
following usage is more flexible way for customing the class name:
```js
const expandRow = {
renderer: (row) => ...,
className: (isExpanded, row, rowIndex) => {
if (rowIndex > 2) return 'foo';
return 'bar';
}
};
```
### <a name='parentClassName'>expandRow.parentClassName - [String | Function]</a>
Apply the custom class name on parent row of expanded row. For example:
```js
const expandRow = {
renderer: (row) => ...,
parentClassName: 'foo'
};
```
Below case is more flexible way to custom the class name:
```js
const expandRow = {
renderer: (row) => ...,
parentClassName: (isExpanded, row, rowIndex) => {
if (rowIndex > 2) return 'foo';
return 'bar';
}
};
```

View File

@@ -11,6 +11,8 @@
* [classes)](#classes)
* [bgColor](#bgColor)
* [nonSelectable)](#nonSelectable)
* [nonSelectableStyle](#nonSelectableStyle)
* [nonSelectableClasses](#nonSelectableClasses)
* [clickToSelect)](#clickToSelect)
* [clickToExpand)](#clickToExpand)
* [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>
Allow user to select row by clicking on the row.

View File

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

View File

@@ -140,7 +140,7 @@ const columns = [
text: 'Job Type',
editor: {
type: Type.SELECT,
getOptions: () => [.....]
getOptions: (setOptions, { row, column }) => [.....]
}
}];
@@ -152,7 +152,7 @@ const columns = [
text: 'Job Type',
editor: {
type: Type.SELECT,
getOptions: (setOptions) => {
getOptions: (setOptions, { row, column }) => {
setTimeout(() => setOptions([...]), 1500);
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "react-bootstrap-table2-editor",
"version": "1.2.4",
"version": "1.4.0",
"description": "it's the editor addon for react-bootstrap-table2",
"main": "./lib/index.js",
"scripts": {

View File

@@ -1,5 +1,8 @@
/* eslint disable-next-line: 0 */
/* eslint react/prop-types: 0 */
/* eslint react/require-default-props: 0 */
/* eslint camelcase: 0 */
/* eslint react/no-unused-prop-types: 0 */
import React from 'react';
import PropTypes from 'prop-types';
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.options.errorMessage) {
this.setState(() => ({
@@ -56,12 +59,13 @@ export default (
}
handleCellUpdate(row, column, newValue) {
const newValueWithType = dataOperator.typeConvert(column.type, newValue);
const { cellEdit } = this.props;
const { beforeSaveCell } = cellEdit.options;
const oldValue = _.get(row, column.dataField);
const beforeSaveCellDone = (result = true) => {
if (result) {
this.doUpdate(row, column, newValue);
this.doUpdate(row, column, newValueWithType);
} else {
this.escapeEditing();
}
@@ -69,7 +73,7 @@ export default (
if (_.isFunction(beforeSaveCell)) {
const result = beforeSaveCell(
oldValue,
newValue,
newValueWithType,
row,
column,
beforeSaveCellDone
@@ -78,7 +82,7 @@ export default (
return;
}
}
this.doUpdate(row, column, newValue);
this.doUpdate(row, column, newValueWithType);
}
doUpdate(row, column, newValue) {

View File

@@ -8,7 +8,13 @@ class DropDownEditor extends Component {
super(props);
let options = props.options;
if (props.getOptions) {
options = props.getOptions(this.setOptions.bind(this)) || [];
options = props.getOptions(
this.setOptions.bind(this),
{
row: props.row,
column: props.column
}
) || [];
}
this.state = { options };
}
@@ -54,6 +60,8 @@ class DropDownEditor extends Component {
}
DropDownEditor.propTypes = {
row: PropTypes.object.isRequired,
column: PropTypes.object.isRequired,
defaultValue: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number

View File

@@ -2,6 +2,7 @@
/* eslint no-return-assign: 0 */
/* eslint class-methods-use-this: 0 */
/* eslint jsx-a11y/no-noninteractive-element-interactions: 0 */
/* eslint camelcase: 0 */
import React, { Component } from 'react';
import cs from 'classnames';
import PropTypes from 'prop-types';
@@ -51,7 +52,11 @@ export default (_, onStartEdit) =>
};
}
componentWillReceiveProps({ message }) {
componentWillUnmount() {
this.clearTimer();
}
UNSAFE_componentWillReceiveProps({ message }) {
if (_.isDefined(message)) {
this.createTimer();
this.setState(() => ({
@@ -60,10 +65,6 @@ export default (_, onStartEdit) =>
}
}
componentWillUnmount() {
this.clearTimer();
}
clearTimer() {
if (this.indicatorTimer) {
clearTimeout(this.indicatorTimer);
@@ -201,7 +202,7 @@ export default (_, onStartEdit) =>
if (_.isFunction(column.editorRenderer)) {
editor = column.editorRenderer(editorProps, value, row, column, rowIndex, columnIndex);
} else if (isDefaultEditorDefined && column.editor.type === EDITTYPE.SELECT) {
editor = <DropdownEditor { ...editorProps } />;
editor = <DropdownEditor { ...editorProps } row={ row } column={ column } />;
} else if (isDefaultEditorDefined && column.editor.type === EDITTYPE.TEXTAREA) {
editor = <TextAreaEditor { ...editorProps } autoSelectText={ autoSelectText } />;
} else if (isDefaultEditorDefined && column.editor.type === EDITTYPE.CHECKBOX) {

View File

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

View File

@@ -0,0 +1,123 @@
/* eslint prefer-template: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import cellEditFactory, { Type } from 'react-bootstrap-table2-editor';
import Code from 'components/common/code-block';
import { stockGenerator } from 'utils/common';
const products = stockGenerator();
const columns = [{
dataField: 'id',
text: 'Stock ID'
}, {
dataField: 'name',
text: 'Stock Name'
}, {
dataField: 'price',
text: 'Price',
type: 'number'
}, {
dataField: 'visible',
text: 'Visible?',
type: 'bool',
editor: {
type: Type.CHECKBOX,
value: 'true:false'
}
}, {
dataField: 'inStockDate',
text: 'Stock Date',
type: 'date',
formatter: (cell) => {
let dateObj = cell;
if (typeof cell !== 'object') {
dateObj = new Date(cell);
}
return `${('0' + dateObj.getUTCDate()).slice(-2)}/${('0' + (dateObj.getUTCMonth() + 1)).slice(-2)}/${dateObj.getUTCFullYear()}`;
},
editor: {
type: Type.DATE
}
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
import cellEditFactory from 'react-bootstrap-table2-editor';
const columns = [{
dataField: 'id',
text: 'Stock ID'
}, {
dataField: 'name',
text: 'Stock Name'
}, {
dataField: 'price',
text: 'Price',
type: 'number'
}, {
dataField: 'visible',
text: 'Visible?',
type: 'bool',
editor: {
type: Type.CHECKBOX,
value: 'true:false'
}
}, {
dataField: 'inStockDate',
text: 'Stock Date',
type: 'date',
formatter: (cell) => {
let dateObj = cell;
if (typeof cell !== 'object') {
dateObj = new Date(cell);
}
return \`$\{('0' + dateObj.getUTCDate()).slice(-2)}/$\{('0' + (dateObj.getUTCMonth() + 1)).slice(-2)}/$\{dateObj.getUTCFullYear()}\`;
},
editor: {
type: Type.DATE
}
}];
function afterSaveCell(oldValue, newValue) {
console.log('--after save cell--');
console.log('New Value was apply as');
console.log(newValue);
console.log(\`and the type is $\{typeof newValue}\`);
}
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
cellEdit={ cellEditFactory({
mode: 'click',
blurToSave: true,
afterSaveCell
}) }
/>
`;
function afterSaveCell(oldValue, newValue) {
console.log('--after save cell--');
console.log('New Value was apply as');
console.log(newValue);
console.log(`and the type is ${typeof newValue}`);
}
export default () => (
<div>
<h3>Save Cell Value with Specified Data Type</h3>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
cellEdit={ cellEditFactory({
mode: 'click',
blurToSave: true,
afterSaveCell
}) }
/>
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -1,3 +1,4 @@
/* eslint no-console: 0 */
/* eslint react/prefer-stateless-function: 0 */
import React from 'react';
@@ -25,22 +26,26 @@ const columns = [{
text: 'Job Type1',
editor: {
type: Type.SELECT,
getOptions: () => [{
value: 'A',
label: 'A'
}, {
value: 'B',
label: 'B'
}, {
value: 'C',
label: 'C'
}, {
value: 'D',
label: 'D'
}, {
value: 'E',
label: 'E'
}]
getOptions: (setOptions, { row, column }) => {
console.log(`current editing row id: ${row.id}`);
console.log(`current editing column: ${column.dataField}`);
return [{
value: 'A',
label: 'A'
}, {
value: 'B',
label: 'B'
}, {
value: 'C',
label: 'C'
}, {
value: 'D',
label: 'D'
}, {
value: 'E',
label: 'E'
}];
}
}
}, {
dataField: 'type2',
@@ -88,22 +93,26 @@ const columns = [{
text: 'Job Type1',
editor: {
type: Type.SELECT,
getOptions: () => [{
value: 'A',
label: 'A'
}, {
value: 'B',
label: 'B'
}, {
value: 'C',
label: 'C'
}, {
value: 'D',
label: 'D'
}, {
value: 'E',
label: 'E'
}]
getOptions: (setOptions, { row, column }) => {
console.log(\`current editing row id: $\{row.id}\`);
console.log(\`current editing column: $\{column.dataField}\`);
return [{
value: 'A',
label: 'A'
}, {
value: 'B',
label: 'B'
}, {
value: 'C',
label: 'C'
}, {
value: 'D',
label: 'D'
}, {
value: 'E',
label: 'E'
}];
}
}
}, {
dataField: 'type2',

View File

@@ -12,8 +12,12 @@ import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
class Table extends React.Component {
filterByPrice = filterVal =>
products.filter(product => product.price == filterVal);
filterByPrice = (filterVal, data) => {
if (filterVal) {
return data.filter(product => product.price == filterVal);
}
return data;
}
render() {
const columns = [{
@@ -46,8 +50,12 @@ class Table extends React.Component {
`;
export default class Table extends React.Component {
filterByPrice = filterVal =>
products.filter(product => product.price == filterVal);
filterByPrice = (filterVal, data) => {
if (filterVal) {
return data.filter(product => product.price == filterVal);
}
return data;
}
render() {
const columns = [{
@@ -67,7 +75,7 @@ export default class Table extends React.Component {
return (
<div>
<h2>Implement a eq filter on product price column</h2>
<h2>Implement a eq price filter</h2>
<BootstrapTable
keyField="id"
data={ products }

View File

@@ -0,0 +1,93 @@
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"
/>
`;
export default () => (
<div>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="top"
/>
<Code>{ sourceCode1 }</Code>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
filter={ filterFactory() }
filterPosition="bottom"
/>
<Code>{ sourceCode2 }</Code>
</div>
);

View File

@@ -0,0 +1,150 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { selectFilter } from 'react-bootstrap-table2-filter';
import Code from 'components/common/code-block';
import { productsQualityGenerator } from 'utils/common';
const products = productsQualityGenerator(6);
const selectOptions = {
0: 'good',
1: 'Bad',
2: 'unknown'
};
const selectOptionsArr = [{
value: 0,
label: 'good'
}, {
value: 1,
label: 'Bad'
}, {
value: 2,
label: 'unknown'
}];
const columns1 = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptions[cell],
filter: selectFilter({
options: selectOptions
})
}];
const columns2 = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptionsArr.filter(opt => opt.value === cell)[0].label || '',
filter: selectFilter({
options: selectOptionsArr
})
}];
const columns3 = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptionsArr.filter(opt => opt.value === cell)[0].label || '',
filter: selectFilter({
options: () => selectOptionsArr
})
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { selectFilter } from 'react-bootstrap-table2-filter';
// Object map options
const selectOptions = {
0: 'good',
1: 'Bad',
2: 'unknown'
};
// Array options
const selectOptionsArr = [{
value: 0,
label: 'good'
}, {
value: 1,
label: 'Bad'
}, {
value: 2,
label: 'unknown'
}];
const columns1 = [..., {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptions[cell],
filter: selectFilter({
options: selectOptions
})
}];
<BootstrapTable keyField='id' data={ products } columns={ columns1 } filter={ filterFactory() } />
const columns2 = [..., {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptionsArr.filter(opt => opt.value === cell)[0].label || '',
filter: selectFilter({
options: selectOptionsArr
})
}];
<BootstrapTable keyField='id' data={ products } columns={ columns2 } filter={ filterFactory() } />
const columns3 = [..., {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptionsArr.filter(opt => opt.value === cell)[0].label || '',
filter: selectFilter({
options: () => selectOptionsArr
})
}];
<BootstrapTable keyField='id' data={ products } columns={ columns3 } filter={ filterFactory() } />
`;
export default () => (
<div>
<h2>Options as an object</h2>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns1 }
filter={ filterFactory() }
/>
<h2>Options as an array</h2>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns2 }
filter={ filterFactory() }
/>
<h2>Options as a function which return an array</h2>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns3 }
filter={ filterFactory() }
/>
<Code>{ sourceCode }</Code>
</div>
);

View File

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

View File

@@ -0,0 +1,94 @@
/* eslint react/prop-types: 0 */
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import ToolkitProvider, { ColumnToggle } from 'react-bootstrap-table2-toolkit';
import Code from 'components/common/code-block';
import { productsGenerator } from 'utils/common';
const { ToggleList } = ColumnToggle;
const products = productsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name',
sort: true,
filter: textFilter()
}, {
dataField: 'price',
text: 'Product Price',
sort: true,
filter: textFilter()
}];
const sourceCode = `\
import BootstrapTable from 'react-bootstrap-table-next';
import filterFactory, { textFilter } from 'react-bootstrap-table2-filter';
import ToolkitProvider, { ColumnToggle } from 'react-bootstrap-table2-toolkit';
const { ToggleList } = ColumnToggle;
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name',
sort: true,
filter: textFilter()
}, {
dataField: 'price',
text: 'Product Price',
sort: true,
filter: textFilter()
}];
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
columnToggle
>
{
props => (
<div>
<ToggleList { ...props.columnToggleProps } />
<hr />
<BootstrapTable
{ ...props.baseProps }
filter={ filterFactory() }
/>
</div>
)
}
</ToolkitProvider>
`;
export default () => (
<div>
<h3>Table will keep the filter/sort state when column toggle</h3>
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
columnToggle
>
{
props => (
<div>
<ToggleList { ...props.columnToggleProps } />
<hr />
<BootstrapTable
{ ...props.baseProps }
filter={ filterFactory() }
/>
</div>
)
}
</ToolkitProvider>
<Code>{ sourceCode }</Code>
</div>
);

View File

@@ -0,0 +1,188 @@
/* eslint no-param-reassign: 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 DummyColumnWithRowExpand extends React.Component {
constructor(props) {
super(props);
this.state = {
hoverIdx: null
};
}
expandRow = {
renderer: () => (
<div style={ { width: '100%', height: '20px' } }>Content</div>
),
showExpandColumn: true,
expandByColumnOnly: true
};
actionFormater = (cell, row, rowIndex, { hoverIdx }) => {
if ((hoverIdx !== null || hoverIdx !== undefined) && hoverIdx === rowIndex) {
return (
<div
style={ { width: '20px', height: '20px', backgroundColor: 'orange' } }
/>
);
}
return (
<div
style={ { width: '20px', height: '20px' } }
/>
);
}
rowEvents = {
onMouseEnter: (e, row, rowIndex) => {
this.setState({ hoverIdx: rowIndex });
},
onMouseLeave: () => {
this.setState({ hoverIdx: null });
}
}
rowStyle = (row, rowIndex) => {
row.index = rowIndex;
const style = {};
if (rowIndex % 2 === 0) {
style.backgroundColor = 'transparent';
} else {
style.backgroundColor = 'rgba(54, 163, 173, .10)';
}
style.borderTop = 'none';
return style;
}
render() {
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}, {
text: '',
isDummyField: true,
formatter: this.actionFormater,
formatExtraData: { hoverIdx: this.state.hoverIdx },
headerStyle: { width: '50px' },
style: { height: '30px' }
}];
return (
<div>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
noDataIndication="There is no data"
classes="table"
rowStyle={ this.rowStyle }
rowEvents={ this.rowEvents }
expandRow={ this.expandRow }
/>
</div>
);
}
}
`;
export default class DummyColumnWithRowExpand extends React.Component {
constructor(props) {
super(props);
this.state = {
hoverIdx: null
};
}
expandRow = {
renderer: () => (
<div style={ { width: '100%', height: '20px' } }>Content</div>
),
showExpandColumn: true,
expandByColumnOnly: true
};
actionFormater = (cell, row, rowIndex, { hoverIdx }) => {
if ((hoverIdx !== null || hoverIdx !== undefined) && hoverIdx === rowIndex) {
return (
<div
style={ { width: '20px', height: '20px', backgroundColor: 'orange' } }
/>
);
}
return (
<div
style={ { width: '20px', height: '20px' } }
/>
);
}
rowEvents = {
onMouseEnter: (e, row, rowIndex) => {
this.setState({ hoverIdx: rowIndex });
},
onMouseLeave: () => {
this.setState({ hoverIdx: null });
}
}
rowStyle = (row, rowIndex) => {
row.index = rowIndex;
const style = {};
if (rowIndex % 2 === 0) {
style.backgroundColor = 'transparent';
} else {
style.backgroundColor = 'rgba(54, 163, 173, .10)';
}
style.borderTop = 'none';
return style;
}
render() {
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}, {
isDummyField: true,
text: '',
formatter: this.actionFormater,
formatExtraData: { hoverIdx: this.state.hoverIdx },
headerStyle: { width: '50px' },
style: { height: '30px' }
}];
return (
<div>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
rowStyle={ this.rowStyle }
rowEvents={ this.rowEvents }
expandRow={ this.expandRow }
/>
<Code>{ sourceCode }</Code>
</div>
);
}
}

View File

@@ -36,11 +36,12 @@ const columns = [{
const MyExportCSV = (props) => {
const handleClick = () => {
props.onExport();
// passing my custom data
props.onExport(products.filter(r => r.id > 2));
};
return (
<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>
);
};

View File

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

View File

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

View File

@@ -36,7 +36,7 @@ const RemotePagination = ({ loading, data, page, sizePerPage, onTableChange, tot
columns={ columns }
pagination={ paginationFactory({ page, sizePerPage, totalSize }) }
onTableChange={ onTableChange }
overlay={ overlayFactory({ spinner: true, background: 'rgba(192,192,192,0.3)' }) }
overlay={ overlayFactory({ spinner: true, styles: { overlay: (base) => ({...base, background: 'rgba(255, 0, 0, 0.5)'}) } }) }
/>
<Code>{ sourceCode }</Code>
</div>
@@ -101,7 +101,12 @@ const RemotePagination = ({ loading, data, page, sizePerPage, onTableChange, tot
columns={ columns }
pagination={ paginationFactory({ page, sizePerPage, totalSize }) }
onTableChange={ onTableChange }
overlay={ overlayFactory({ spinner: true, background: 'rgba(192,192,192,0.3)' }) }
overlay={
overlayFactory({
spinner: true,
styles: { overlay: base => ({ ...base, background: 'rgba(255, 0, 0, 0.5)' }) }
})
}
/>
<Code>{ sourceCode }</Code>
</div>

View File

@@ -74,7 +74,7 @@ const options = {
// hidePageListOnlyOnePage: true, // Hide the pagination list when only one page
firstPageText: 'First',
prePageText: 'Back',
nextPageText: 'Next',
nextPageText: <span>Next</span>,
lastPageText: 'Last',
nextPageTitle: 'First page',
prePageTitle: 'Pre page',

View File

@@ -0,0 +1,106 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsExpandRowsGenerator } from 'utils/common';
const products = productsExpandRowsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const expandRow1 = {
className: 'expanding-foo',
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>
)
};
const expandRow2 = {
className: (isExpanded, row, rowIndex) => {
if (rowIndex > 2) return 'expanding-foo';
return 'expanding-bar';
},
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>
)
};
const sourceCode1 = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = // omit...
const expandRow = {
className: 'expanding-foo',
renderer: row => (
<div>.....</div>
)
};
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
expandRow={ expandRow }
/>
`;
const sourceCode2 = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = // omit...
const expandRow = {
className: (isExpanded, row, rowIndex) => {
if (rowIndex > 2) return 'expanding-foo';
return 'expanding-bar';
},
renderer: row => (
<div>...</div>
)
};
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
expandRow={ expandRow }
/>
`;
export default () => (
<div>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
expandRow={ expandRow1 }
/>
<Code>{ sourceCode1 }</Code>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
expandRow={ expandRow2 }
/>
<Code>{ sourceCode2 }</Code>
</div>
);

View File

@@ -18,9 +18,9 @@ const columns = [{
}];
const expandRow = {
renderer: row => (
renderer: (row, rowIndex) => (
<div>
<p>{ `This Expand row is belong to rowKey ${row.id}` }</p>
<p>{ `This Expand row is belong to rowKey ${row.id} and index: ${rowIndex}` }</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>

View File

@@ -0,0 +1,106 @@
import React from 'react';
import BootstrapTable from 'react-bootstrap-table-next';
import Code from 'components/common/code-block';
import { productsExpandRowsGenerator } from 'utils/common';
const products = productsExpandRowsGenerator();
const columns = [{
dataField: 'id',
text: 'Product ID'
}, {
dataField: 'name',
text: 'Product Name'
}, {
dataField: 'price',
text: 'Product Price'
}];
const expandRow1 = {
parentClassName: 'parent-expand-foo',
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>
)
};
const expandRow2 = {
parentClassName: (isExpanded, row, rowIndex) => {
if (rowIndex > 2) return 'parent-expand-foo';
return 'parent-expand-bar';
},
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>
)
};
const sourceCode1 = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = // omit...
const expandRow = {
parentClassName: 'parent-expand-foo',
renderer: row => (
<div>.....</div>
)
};
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
expandRow={ expandRow }
/>
`;
const sourceCode2 = `\
import BootstrapTable from 'react-bootstrap-table-next';
const columns = // omit...
const expandRow = {
parentClassName: (isExpanded, row, rowIndex) => {
if (rowIndex > 2) return 'parent-expand-foo';
return 'parent-expand-bar';
},
renderer: row => (
<div>...</div>
)
};
<BootstrapTable
keyField='id'
data={ products }
columns={ columns }
expandRow={ expandRow }
/>
`;
export default () => (
<div>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
expandRow={ expandRow1 }
/>
<Code>{ sourceCode1 }</Code>
<BootstrapTable
keyField="id"
data={ products }
columns={ columns }
expandRow={ expandRow2 }
/>
<Code>{ sourceCode2 }</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],
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,87 @@
/* eslint react/prop-types: 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',
searchable: false
}, {
dataField: 'price',
text: 'Product Price',
searchable: false
}];
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',
searchable: false
}, {
dataField: 'price',
text: 'Product Price',
searchable: false
}];
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
search
>
{
props => (
<div>
<h3>Input something at below input field:</h3>
<SearchBar { ...props.searchProps } />
<hr />
<BootstrapTable
{ ...props.baseProps }
/>
</div>
)
}
</ToolkitProvider>
`;
export default () => (
<div>
<ToolkitProvider
keyField="id"
data={ products }
columns={ columns }
search
>
{
props => (
<div>
<h3>Column name and price is unsearchable</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

@@ -1,6 +1,6 @@
{
"name": "react-bootstrap-table2-example",
"version": "1.0.26",
"version": "1.0.34",
"description": "",
"main": "index.js",
"private": true,

View File

@@ -29,6 +29,11 @@ export const withOnSale = rows => rows.map((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) =>
Array.from({ length: quantity }, (value, index) => ({
id: index + factor,
@@ -69,8 +74,9 @@ const endDate = new Date();
export const stockGenerator = (quantity = 5) =>
Array.from({ length: quantity }, (value, index) => ({
id: index,
name: `Todo item ${index}`,
name: `Stock Name ${index}`,
price: Math.floor((Math.random() * 2) + 1),
visible: Math.random() > 0.5,
inStockDate:
new Date(startDate.getTime() + Math.random() * (endDate.getTime() - startDate.getTime()))
}));

View File

@@ -35,6 +35,7 @@ import ColumnEventTable from 'examples/columns/column-event-table';
import ColumnHiddenTable from 'examples/columns/column-hidden-table';
import ColumnAttrsTable from 'examples/columns/column-attrs-table';
import DummyColumnTable from 'examples/columns/dummy-column-table';
import RowExpandWithFormattedDummyColumn from 'examples/columns/row-expand-with-formatted-dummy-column.js';
// work on header columns
import HeaderColumnFormatTable from 'examples/header-columns/column-format-table';
@@ -67,6 +68,7 @@ import TextFilterCaseSensitive from 'examples/column-filter/text-filter-caseSens
import CustomTextFilter from 'examples/column-filter/custom-text-filter';
import CustomFilterValue from 'examples/column-filter/custom-filter-value';
import SelectFilter from 'examples/column-filter/select-filter';
import ConfigureSelectFilterOptions from 'examples/column-filter/select-filter-option-type';
import SelectFilterWithDefaultValue from 'examples/column-filter/select-filter-default-value';
import SelectFilterComparator from 'examples/column-filter/select-filter-like-comparator';
import SelectFilterWithPreservedOptionsOrder from 'examples/column-filter/select-filter-preserve-option-order';
@@ -90,6 +92,7 @@ import AdvanceCustomFilter from 'examples/column-filter/advance-custom-filter';
import ClearAllFilters from 'examples/column-filter/clear-all-filters';
import FilterHooks from 'examples/column-filter/filter-hooks';
import CustomFilterLogic from 'examples/column-filter/custom-filter-logic';
import FilterPosition from 'examples/column-filter/filter-position';
// work on rows
import RowStyleTable from 'examples/rows/row-style';
@@ -102,6 +105,7 @@ import EnableSortTable from 'examples/sort/enable-sort-table';
import DefaultSortTable from 'examples/sort/default-sort-table';
import DefaultSortDirectionTable from 'examples/sort/default-sort-direction';
import SortEvents from 'examples/sort/sort-events';
import CustomSortValue from 'examples/sort/custom-sort-value';
import CustomSortTable from 'examples/sort/custom-sort-table';
import CustomSortCaretTable from 'examples/sort/custom-sort-caret';
import HeaderSortingClassesTable from 'examples/sort/header-sorting-classes';
@@ -130,6 +134,7 @@ import TextareaEditorTable from 'examples/cell-edit/textarea-editor-table';
import CheckboxEditorTable from 'examples/cell-edit/checkbox-editor-table';
import DateEditorTable from 'examples/cell-edit/date-editor-table';
import CustomEditorTable from 'examples/cell-edit/custom-editor-table';
import CellEditorWithDataType from 'examples/cell-edit/cell-edit-with-data-type';
// work on row selection
import SingleSelectionTable from 'examples/row-selection/single-selection';
@@ -147,6 +152,8 @@ import HeaderStyleTable from 'examples/row-selection/header-style';
import HideSelectAllTable from 'examples/row-selection/hide-select-all';
import CustomSelectionTable from 'examples/row-selection/custom-selection';
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 SelectionHooks from 'examples/row-selection/selection-hooks';
import HideSelectionColumnTable from 'examples/row-selection/hide-selection-column';
@@ -163,6 +170,8 @@ import ExpandOnlyOne from 'examples/row-expand/expand-only-one';
import CustomExpandColumn from 'examples/row-expand/custom-expand-column';
import ExpandColumnPosition from 'examples/row-expand/expand-column-position';
import ExpandHooks from 'examples/row-expand/expand-hooks';
import ParentRowClassName from 'examples/row-expand/parent-row-classname';
import ExpandingRowClassName from 'examples/row-expand/expanding-row-classname';
// pagination
import PaginationTable from 'examples/pagination';
@@ -189,6 +198,8 @@ import DefaultCustomSearch from 'examples/search/default-custom-search';
import FullyCustomSearch from 'examples/search/fully-custom-search';
import SearchFormattedData from 'examples/search/search-formatted';
import CustomSearchValue from 'examples/search/custom-search-value';
import SearchableColumn from 'examples/search/searchable-column';
import CustomMatchFunction from 'examples/search/custom-match-function';
// CSV
import ExportCSV from 'examples/csv';
@@ -207,6 +218,7 @@ import BasicColumnToggle from 'examples/column-toggle';
import DefaultVisibility from 'examples/column-toggle/default-visibility';
import StylingColumnToggle from 'examples/column-toggle/styling-toggle-list';
import CustomToggleList from 'examples/column-toggle/custom-toggle-list';
import ColumnToggleWithFilter from 'examples/column-toggle/column-toggle-with-filter';
// loading overlay
import EmptyTableOverlay from 'examples/loading-overlay/empty-table-overlay';
@@ -273,7 +285,8 @@ storiesOf('Work on Columns', module)
.add('Customize Column Class', () => <ColumnClassTable />)
.add('Customize Column Style', () => <ColumnStyleTable />)
.add('Customize Column HTML attribute', () => <ColumnAttrsTable />)
.add('Dummy Column', () => <DummyColumnTable />);
.add('Dummy Column', () => <DummyColumnTable />)
.add('Row Expand with Dummy Column Formatter', () => <RowExpandWithFormattedDummyColumn />);
storiesOf('Work on Header Columns', module)
.addDecorator(bootstrapStyle())
@@ -295,6 +308,7 @@ storiesOf('Column Filter', module)
.add('Text Filter with Case Sensitive', () => <TextFilterCaseSensitive />)
// add another filter type example right here.
.add('Select Filter', () => <SelectFilter />)
.add('Configure Select Filter Options', () => <ConfigureSelectFilterOptions />)
.add('Select Filter with Default Value', () => <SelectFilterWithDefaultValue />)
.add('Select Filter with Comparator', () => <SelectFilterComparator />)
.add('MultiSelect Filter', () => <MultiSelectFilter />)
@@ -303,6 +317,7 @@ storiesOf('Column Filter', module)
.add('Number Filter with Default Value', () => <NumberFilterWithDefaultValue />)
.add('Date Filter', () => <DateFilter />)
.add('Date Filter with Default Value', () => <DateFilterWithDefaultValue />)
.add('Filter Position', () => <FilterPosition />)
.add('Custom Text Filter', () => <CustomTextFilter />)
.add('Custom Select Filter', () => <CustomSelectFilter />)
.add('Custom Number Filter', () => <CustomNumberFilter />)
@@ -347,6 +362,7 @@ storiesOf('Sort Table', module)
.add('Default Sort Table', () => <DefaultSortTable />)
.add('Default Sort Direction Table', () => <DefaultSortDirectionTable />)
.add('Sort Events', () => <SortEvents />)
.add('Custom Sort Value', () => <CustomSortValue />)
.add('Custom Sort Fuction', () => <CustomSortTable />)
.add('Custom Sort Caret', () => <CustomSortCaretTable />)
.add('Custom Classes on Sorting Header Column', () => <HeaderSortingClassesTable />)
@@ -375,7 +391,8 @@ storiesOf('Cell Editing', module)
.add('Textarea Editor', () => <TextareaEditorTable />)
.add('Checkbox Editor', () => <CheckboxEditorTable />)
.add('Date Editor', () => <DateEditorTable />)
.add('Custom Editor', () => <CustomEditorTable />);
.add('Custom Editor', () => <CustomEditorTable />)
.add('Cell Editor with Data Type', () => <CellEditorWithDataType />);
storiesOf('Row Selection', module)
.addDecorator(bootstrapStyle())
@@ -395,6 +412,8 @@ storiesOf('Row Selection', module)
.add('Custom Selection', () => <CustomSelectionTable />)
.add('Selection Background Color', () => <SelectionBgColorTable />)
.add('Not Selectabled Rows', () => <NonSelectableRowsTable />)
.add('Not Selectabled Rows Style', () => <NonSelectableRowsStyleTable />)
.add('Not Selectabled Rows Class', () => <NonSelectableRowsClassTable />)
.add('Selection Hooks', () => <SelectionHooks />)
.add('Hide Selection Column', () => <HideSelectionColumnTable />)
.add('Custom Selection Column Style', () => <SelectionColumnStyleTable />)
@@ -410,7 +429,9 @@ storiesOf('Row Expand', module)
.add('Expand Only One Row at The Same Time', () => <ExpandOnlyOne />)
.add('Custom Expand Indicator', () => <CustomExpandColumn />)
.add('Expand Column Position', () => <ExpandColumnPosition />)
.add('Expand Hooks', () => <ExpandHooks />);
.add('Expand Hooks', () => <ExpandHooks />)
.add('Custom Parent Row ClassName', () => <ParentRowClassName />)
.add('Custom Expanding Row ClassName', () => <ExpandingRowClassName />);
storiesOf('Pagination', module)
.addDecorator(bootstrapStyle())
@@ -436,16 +457,19 @@ storiesOf('Table Search', module)
.add('Clear Search Button', () => <ClearSearchButton />)
.add('Default Search Table', () => <DefaultSearch />)
.add('Default Custom Search', () => <DefaultCustomSearch />)
.add('Searchable Column', () => <SearchableColumn />)
.add('Fully Custom Search', () => <FullyCustomSearch />)
.add('Search Fromatted Value', () => <SearchFormattedData />)
.add('Custom Search Value', () => <CustomSearchValue />);
.add('Search Formatted Value', () => <SearchFormattedData />)
.add('Custom Search Value', () => <CustomSearchValue />)
.add('Custom match function', () => <CustomMatchFunction />);
storiesOf('Column Toggle', module)
.addDecorator(bootstrapStyle())
.add('Basic Column Toggle', () => <BasicColumnToggle />)
.add('Default Visibility', () => <DefaultVisibility />)
.add('Styling Column Toggle', () => <StylingColumnToggle />)
.add('Custom Column Toggle', () => <CustomToggleList />);
.add('Custom Column Toggle', () => <CustomToggleList />)
.add('Column Toggle with Filter', () => <ColumnToggleWithFilter />);
storiesOf('Export CSV', module)
.addDecorator(bootstrapStyle())

View File

@@ -0,0 +1,7 @@
.expanding-foo, .parent-expand-foo {
background-color: coral;
}
.expanding-bar, .parent-expand-bar {
background-color: aqua;
}

View File

@@ -12,3 +12,4 @@
@import "sort/index";
@import "search/index";
@import "loading-overlay/index";
@import "row-expand/index";

View File

@@ -115,7 +115,9 @@ const qualityFilter = selectFilter({
// omit...
```
> Note, the selectOptions can be an array also:
> Note, the selectOptions can be an array or a function which return an array:
### Array as options
```js
const selectOptions = [
@@ -133,6 +135,24 @@ const columns = [
})
}];
```
### Function as options
```js
const selectOptions = [
{ value: 0, label: 'good' },
{ value: 1, label: 'Bad' },
{ value: 2, label: 'unknown' }
];
const columns = [
..., {
dataField: 'quality',
text: 'Product Quailty',
formatter: cell => selectOptions.find(opt => opt.value === cell).label,
filter: selectFilter({
options: () => selectOptions
})
}];
```
The benifit is `react-bootstrap-table2` will render the select options by the order of array.
@@ -310,3 +330,29 @@ Following properties is valid in `FILTER_TYPES`:
* NUMBER
* DATE
* 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,6 @@
{
"name": "react-bootstrap-table2-filter",
"version": "1.1.9",
"version": "1.3.0",
"description": "it's a column filter addon for react-bootstrap-table2",
"main": "./lib/index.js",
"repository": {

View File

@@ -83,14 +83,27 @@ class DateFilter extends Component {
return optionTags;
}
getDefaultDate() {
let defaultDate = '';
const { defaultValue } = this.props;
if (defaultValue && defaultValue.date) {
// Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
defaultDate = dateParser(new Date(defaultValue.date));
getDefaultComparator() {
const { defaultValue, filterState } = this.props;
if (filterState && filterState.filterVal) {
return filterState.filterVal.comparator;
}
return defaultDate;
if (defaultValue && defaultValue.comparator) {
return defaultValue.comparator;
}
return '';
}
getDefaultDate() {
// Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
const { defaultValue, filterState } = this.props;
if (filterState && filterState.filterVal && filterState.filterVal.date) {
return dateParser(filterState.filterVal.date);
}
if (defaultValue && defaultValue.date) {
return dateParser(new Date(defaultValue.date));
}
return '';
}
applyFilter(value, comparator, isInitial) {
@@ -122,8 +135,7 @@ class DateFilter extends Component {
dateStyle,
className,
comparatorClassName,
dateClassName,
defaultValue
dateClassName
} = this.props;
return (
@@ -143,7 +155,7 @@ class DateFilter extends Component {
style={ comparatorStyle }
className={ `date-filter-comparator form-control ${comparatorClassName}` }
onChange={ this.onChangeComparator }
defaultValue={ defaultValue ? defaultValue.comparator : '' }
defaultValue={ this.getDefaultComparator() }
>
{ this.getComparatorOptions() }
</select>
@@ -169,6 +181,7 @@ class DateFilter extends Component {
DateFilter.propTypes = {
onFilter: PropTypes.func.isRequired,
column: PropTypes.object.isRequired,
filterState: PropTypes.object,
delay: PropTypes.number,
defaultValue: PropTypes.shape({
date: PropTypes.oneOfType([PropTypes.object]),
@@ -210,6 +223,7 @@ DateFilter.defaultProps = {
date: undefined,
comparator: ''
},
filterState: {},
withoutEmptyComparatorOption: false,
comparators: legalComparators,
placeholder: undefined,

View File

@@ -18,8 +18,18 @@ function optionsEquals(currOpts, prevOpts) {
return Object.keys(currOpts).length === Object.keys(prevOpts).length;
}
const getSelections = container =>
Array.from(container.selectedOptions).map(item => item.value);
const getSelections = (container) => {
if (container.selectedOptions) {
return Array.from(container.selectedOptions).map(item => item.value);
}
const selections = [];
const totalLen = container.options.length;
for (let i = 0; i < totalLen; i += 1) {
const option = container.options.item(i);
if (option.selected) selections.push(option.value);
}
return selections;
};
class MultiSelectFilter extends Component {
constructor(props) {
@@ -55,10 +65,18 @@ class MultiSelectFilter extends Component {
needFilter = true;
}
if (needFilter) {
this.applyFilter(this.selectInput.value);
this.applyFilter(getSelections(this.selectInput));
}
}
getDefaultValue() {
const { filterState, defaultValue } = this.props;
if (filterState && typeof filterState.filterVal !== 'undefined') {
return filterState.filterVal;
}
return defaultValue;
}
getOptions() {
const optionTags = [];
const { options, placeholder, column, withoutEmptyOption } = this.props;
@@ -96,6 +114,7 @@ class MultiSelectFilter extends Component {
const {
style,
className,
filterState,
defaultValue,
onFilter,
column,
@@ -125,7 +144,7 @@ class MultiSelectFilter extends Component {
className={ selectClass }
onChange={ this.filter }
onClick={ e => e.stopPropagation() }
defaultValue={ defaultValue !== undefined ? defaultValue : '' }
defaultValue={ this.getDefaultValue() }
>
{ this.getOptions() }
</select>
@@ -138,6 +157,7 @@ MultiSelectFilter.propTypes = {
onFilter: PropTypes.func.isRequired,
column: PropTypes.object.isRequired,
options: PropTypes.object.isRequired,
filterState: PropTypes.object,
comparator: PropTypes.oneOf([LIKE, EQ]),
placeholder: PropTypes.string,
style: PropTypes.object,
@@ -150,6 +170,7 @@ MultiSelectFilter.propTypes = {
MultiSelectFilter.defaultProps = {
defaultValue: [],
filterState: {},
className: '',
withoutEmptyOption: false,
comparator: EQ,

View File

@@ -94,6 +94,28 @@ class NumberFilter extends Component {
onFilter(column, FILTER_TYPE.NUMBER)({ number: value, comparator });
}
getDefaultComparator() {
const { defaultValue, filterState } = this.props;
if (filterState && filterState.filterVal) {
return filterState.filterVal.comparator;
}
if (defaultValue && defaultValue.comparator) {
return defaultValue.comparator;
}
return '';
}
getDefaultValue() {
const { defaultValue, filterState } = this.props;
if (filterState && filterState.filterVal) {
return filterState.filterVal.number;
}
if (defaultValue && defaultValue.number) {
return defaultValue.number;
}
return '';
}
getComparatorOptions() {
const optionTags = [];
const { withoutEmptyComparatorOption } = this.props;
@@ -148,7 +170,6 @@ class NumberFilter extends Component {
render() {
const { isSelected } = this.state;
const {
defaultValue,
column,
options,
style,
@@ -184,7 +205,7 @@ class NumberFilter extends Component {
id={ `number-filter-comparator-${column.text}` }
className={ `number-filter-comparator form-control ${comparatorClassName}` }
onChange={ this.onChangeComparator }
defaultValue={ defaultValue ? defaultValue.comparator : '' }
defaultValue={ this.getDefaultComparator() }
>
{ this.getComparatorOptions() }
</select>
@@ -202,7 +223,7 @@ class NumberFilter extends Component {
style={ numberStyle }
className={ selectClass }
onChange={ this.onChangeNumberSet }
defaultValue={ defaultValue ? defaultValue.number : '' }
defaultValue={ this.getDefaultValue() }
>
{ this.getNumberOptions() }
</select>
@@ -217,7 +238,7 @@ class NumberFilter extends Component {
className={ `number-filter-input form-control ${numberClassName}` }
placeholder={ placeholder || `Enter ${column.text}...` }
onChange={ this.onChangeNumber }
defaultValue={ defaultValue ? defaultValue.number : '' }
defaultValue={ this.getDefaultValue() }
/>
</label>
}
@@ -229,6 +250,7 @@ class NumberFilter extends Component {
NumberFilter.propTypes = {
onFilter: PropTypes.func.isRequired,
column: PropTypes.object.isRequired,
filterState: PropTypes.object,
options: PropTypes.arrayOf(PropTypes.number),
defaultValue: PropTypes.shape({
number: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
@@ -273,6 +295,7 @@ NumberFilter.defaultProps = {
number: undefined,
comparator: ''
},
filterState: {},
withoutEmptyComparatorOption: false,
withoutEmptyNumberOption: false,
comparators: legalComparators,

View File

@@ -1,6 +1,7 @@
/* eslint react/require-default-props: 0 */
/* eslint no-return-assign: 0 */
/* eslint react/no-unused-prop-types: 0 */
/* eslint class-methods-use-this: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { LIKE, EQ } from '../comparison';
@@ -44,7 +45,8 @@ class SelectFilter extends Component {
constructor(props) {
super(props);
this.filter = this.filter.bind(this);
const isSelected = getOptionValue(props.options, props.defaultValue) !== undefined;
this.options = this.getOptions(props);
const isSelected = getOptionValue(this.options, this.getDefaultValue()) !== undefined;
this.state = { isSelected };
}
@@ -69,36 +71,36 @@ class SelectFilter extends Component {
componentDidUpdate(prevProps) {
let needFilter = false;
if (this.props.defaultValue !== prevProps.defaultValue) {
const {
column,
onFilter,
defaultValue
} = this.props;
const nextOptions = this.getOptions(this.props);
if (defaultValue !== prevProps.defaultValue) {
needFilter = true;
} else if (!optionsEquals(this.props.options, prevProps.options)) {
} else if (!optionsEquals(nextOptions, this.options)) {
this.options = nextOptions;
needFilter = true;
}
if (needFilter) {
const value = this.selectInput.value;
if (value) {
this.props.onFilter(this.props.column, FILTER_TYPE.SELECT)(value);
onFilter(column, FILTER_TYPE.SELECT)(value);
}
}
}
getOptions() {
const optionTags = [];
const { options, placeholder, column, withoutEmptyOption } = this.props;
if (!withoutEmptyOption) {
optionTags.push((
<option key="-1" value="">{ placeholder || `Select ${column.text}...` }</option>
));
getOptions(props) {
return typeof props.options === 'function' ? props.options(props.column) : props.options;
}
getDefaultValue() {
const { filterState, defaultValue } = this.props;
if (filterState && typeof filterState.filterVal !== 'undefined') {
return filterState.filterVal;
}
if (Array.isArray(options)) {
options.forEach(({ value, label }) =>
optionTags.push(<option key={ value } value={ value }>{ label }</option>));
} else {
Object.keys(options).forEach(key =>
optionTags.push(<option key={ key } value={ key }>{ options[key] }</option>)
);
}
return optionTags;
return defaultValue;
}
cleanFiltered() {
@@ -120,6 +122,26 @@ class SelectFilter extends Component {
this.props.onFilter(this.props.column, FILTER_TYPE.SELECT)(value);
}
renderOptions() {
const optionTags = [];
const { options } = this;
const { placeholder, column, withoutEmptyOption } = this.props;
if (!withoutEmptyOption) {
optionTags.push((
<option key="-1" value="">{ placeholder || `Select ${column.text}...` }</option>
));
}
if (Array.isArray(options)) {
options.forEach(({ value, label }) =>
optionTags.push(<option key={ value } value={ value }>{ label }</option>));
} else {
Object.keys(options).forEach(key =>
optionTags.push(<option key={ key } value={ key }>{ options[key] }</option>)
);
}
return optionTags;
}
render() {
const {
style,
@@ -132,6 +154,7 @@ class SelectFilter extends Component {
withoutEmptyOption,
caseSensitive,
getFilter,
filterState,
...rest
} = this.props;
@@ -152,9 +175,9 @@ class SelectFilter extends Component {
className={ selectClass }
onChange={ this.filter }
onClick={ e => e.stopPropagation() }
defaultValue={ defaultValue !== undefined ? defaultValue : '' }
defaultValue={ this.getDefaultValue() || '' }
>
{ this.getOptions() }
{ this.renderOptions() }
</select>
</label>
);
@@ -164,6 +187,7 @@ class SelectFilter extends Component {
SelectFilter.propTypes = {
onFilter: PropTypes.func.isRequired,
column: PropTypes.object.isRequired,
filterState: PropTypes.object,
options: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
comparator: PropTypes.oneOf([LIKE, EQ]),
placeholder: PropTypes.string,
@@ -177,6 +201,7 @@ SelectFilter.propTypes = {
SelectFilter.defaultProps = {
defaultValue: '',
filterState: {},
className: '',
withoutEmptyOption: false,
comparator: EQ,

View File

@@ -1,6 +1,7 @@
/* eslint react/require-default-props: 0 */
/* eslint react/prop-types: 0 */
/* eslint no-return-assign: 0 */
/* eslint camelcase: 0 */
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
@@ -13,8 +14,14 @@ class TextFilter extends Component {
this.filter = this.filter.bind(this);
this.handleClick = this.handleClick.bind(this);
this.timeout = null;
function getDefaultValue() {
if (props.filterState && typeof props.filterState.filterVal !== 'undefined') {
return props.filterState.filterVal;
}
return props.defaultValue;
}
this.state = {
value: props.defaultValue
value: getDefaultValue()
};
}
@@ -35,16 +42,16 @@ class TextFilter extends Component {
}
}
componentWillReceiveProps(nextProps) {
componentWillUnmount() {
this.cleanTimer();
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.defaultValue !== this.props.defaultValue) {
this.applyFilter(nextProps.defaultValue);
}
}
componentWillUnmount() {
this.cleanTimer();
}
filter(e) {
e.stopPropagation();
this.cleanTimer();
@@ -89,6 +96,7 @@ class TextFilter extends Component {
caseSensitive,
defaultValue,
getFilter,
filterState,
...rest
} = this.props;
@@ -119,6 +127,7 @@ class TextFilter extends Component {
TextFilter.propTypes = {
onFilter: PropTypes.func.isRequired,
column: PropTypes.object.isRequired,
filterState: PropTypes.object,
comparator: PropTypes.oneOf([LIKE, EQ]),
defaultValue: PropTypes.string,
delay: PropTypes.number,
@@ -131,6 +140,7 @@ TextFilter.propTypes = {
TextFilter.defaultProps = {
delay: FILTER_DELAY,
filterState: {},
defaultValue: '',
caseSensitive: false
};

View File

@@ -1,5 +1,6 @@
/* eslint react/prop-types: 0 */
/* eslint react/require-default-props: 0 */
/* eslint camelcase: 0 */
import React from 'react';
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, undefined, this.isEmitDataChange);
} else {
this.data = nextProps.data;
}
}
onFilter(column, filterType, initialize = false) {
return (filterVal) => {
// watch out here if migration to context API, #334
@@ -76,12 +68,7 @@ export default (
}
return;
}
let result;
if (filter.props.onFilter) {
result = filter.props.onFilter(filterVal);
}
this.doFilter(this.props, result);
this.doFilter(this.props);
};
}
@@ -95,11 +82,18 @@ export default (
return this.data;
}
doFilter(props, customResult, ignoreEmitDataChange = false) {
let result = customResult;
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) {
const { dataChangeListener, data, columns } = props;
result = result || filters(data, columns, _)(this.currFilters);
const result = filters(data, columns, _)(this.currFilters);
this.data = result;
if (dataChangeListener && !ignoreEmitDataChange) {
this.isEmitDataChange = true;
@@ -115,7 +109,8 @@ export default (
<FilterContext.Provider value={ {
data: this.data,
onFilter: this.onFilter,
onExternalFilter: this.onExternalFilter
onExternalFilter: this.onExternalFilter,
currFilters: this.currFilters
} }
>
{ this.props.children }

View File

@@ -234,16 +234,28 @@ export const filters = (data, columns, _) => (currFilters) => {
let result = data;
let filterFn;
Object.keys(currFilters).forEach((dataField) => {
let currentResult;
const filterObj = currFilters[dataField];
filterFn = factory(filterObj.filterType);
let filterValue;
let customFilter;
for (let i = 0; i < columns.length; i += 1) {
if (columns[i].dataField === dataField) {
filterValue = columns[i].filterValue;
if (columns[i].filter) {
customFilter = columns[i].filter.props.onFilter;
}
break;
}
}
result = filterFn(result, dataField, filterObj, filterValue);
if (customFilter) {
currentResult = customFilter(filterObj.filterVal, result);
}
if (typeof currentResult === 'undefined') {
result = filterFn(result, dataField, filterObj, filterValue);
} else {
result = currentResult;
}
});
return result;
};

View File

@@ -25,7 +25,7 @@ describe('Select Filter', () => {
2: 'Unknown'
};
afterEach(() => {
beforeEach(() => {
onFilter.reset();
onFilterFirstReturn.reset();

View File

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

View File

@@ -94,7 +94,8 @@ describe('FilterContext', () => {
expect(mockBase).toHaveBeenCalledWith({
data,
onFilter: wrapper.instance().onFilter,
onExternalFilter: wrapper.instance().onExternalFilter
onExternalFilter: wrapper.instance().onExternalFilter,
currFilters: wrapper.instance().currFilters
});
});
});
@@ -103,7 +104,6 @@ describe('FilterContext', () => {
beforeEach(() => {
wrapper = shallow(shallowContext(true));
wrapper.render();
wrapper.instance().currFilters = { price: { filterVal: 20, filterType: FILTER_TYPE.TEXT } };
});
it('should pass original data without internal filtering', () => {
@@ -111,7 +111,8 @@ describe('FilterContext', () => {
expect(mockBase).toHaveBeenCalledWith({
data,
onFilter: wrapper.instance().onFilter,
onExternalFilter: wrapper.instance().onExternalFilter
onExternalFilter: wrapper.instance().onExternalFilter,
currFilters: wrapper.instance().currFilters
});
});
});
@@ -228,33 +229,7 @@ describe('FilterContext', () => {
});
});
describe('if filter.props.onFilter is defined', () => {
const filterVal = '3';
const onFilter = jest.fn();
const customColumns = columns.map((column, i) => {
if (i === 1) {
return {
...column,
filter: textFilter({ onFilter })
};
}
return column;
});
beforeEach(() => {
wrapper = shallow(shallowContext(false, customColumns));
wrapper.render();
instance = wrapper.instance();
});
it('should call filter.props.onFilter correctly', () => {
instance.onFilter(customColumns[1], FILTER_TYPE.TEXT)(filterVal);
expect(onFilter).toHaveBeenCalledTimes(1);
expect(onFilter).toHaveBeenCalledWith(filterVal);
});
});
describe('if filter.props.onFilter is defined and return an undefined data', () => {
describe('if filter.props.onFilter is defined and return data', () => {
const mockReturn = [{
id: 1,
name: 'A'
@@ -280,7 +255,7 @@ describe('FilterContext', () => {
it('should call filter.props.onFilter correctly', () => {
instance.onFilter(customColumns[1], FILTER_TYPE.TEXT)(filterVal);
expect(onFilter).toHaveBeenCalledTimes(1);
expect(onFilter).toHaveBeenCalledWith(filterVal);
expect(onFilter).toHaveBeenCalledWith(filterVal, data);
});
it('should set data correctly', () => {

View File

@@ -1,6 +1,6 @@
{
"name": "react-bootstrap-table2-paginator",
"version": "2.0.6",
"version": "2.1.0",
"description": "it's the pagination addon for react-bootstrap-table2",
"main": "./lib/index.js",
"repository": {

View File

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

View File

@@ -39,7 +39,11 @@ class PageButton extends Component {
PageButton.propTypes = {
onPageChange: PropTypes.func.isRequired,
page: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
page: PropTypes.oneOfType([
PropTypes.node,
PropTypes.number,
PropTypes.string
]).isRequired,
active: PropTypes.bool.isRequired,
disabled: PropTypes.bool.isRequired,
className: PropTypes.string,

View File

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

View File

@@ -27,7 +27,11 @@ const PaginatonList = props => (
PaginatonList.propTypes = {
pages: PropTypes.arrayOf(PropTypes.shape({
page: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
page: PropTypes.oneOfType([
PropTypes.node,
PropTypes.number,
PropTypes.string
]),
active: PropTypes.bool,
disable: PropTypes.bool,
title: PropTypes.string

View File

@@ -100,10 +100,10 @@ Pagination.propTypes = {
sizePerPageRenderer: PropTypes.func,
paginationTotalRenderer: PropTypes.func,
sizePerPageOptionRenderer: PropTypes.func,
firstPageText: PropTypes.string,
prePageText: PropTypes.string,
nextPageText: PropTypes.string,
lastPageText: PropTypes.string,
firstPageText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
prePageText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
nextPageText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
lastPageText: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
nextPageTitle: PropTypes.string,
prePageTitle: PropTypes.string,
firstPageTitle: PropTypes.string,

View File

@@ -1,6 +1,7 @@
/* eslint react/prop-types: 0 */
/* eslint react/require-default-props: 0 */
/* eslint no-lonely-if: 0 */
/* eslint camelcase: 0 */
import React from 'react';
import EventEmitter from 'events';
import Const from './const';
@@ -45,23 +46,6 @@ class StateProvider extends React.Component {
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 = () => {
const { pagination: { options }, bootstrap4 } = this.props;
const { currPage, currSizePerPage, dataSize } = this;
@@ -113,6 +97,23 @@ class StateProvider extends React.Component {
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 = () => {
const e = {};
this.remoteEmitter.emit('isRemotePagination', e);

View File

@@ -1,6 +1,6 @@
.react-bootstrap-table-page-btns-ul {
float: right;
margin-top: 0px;
margin-top: 0px !important;
}
.react-bootstrap-table-pagination-list-hidden {

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "react-bootstrap-table2-toolkit",
"version": "2.0.1",
"version": "2.1.0",
"description": "The toolkit for react-bootstrap-table2",
"main": "./lib/index.js",
"repository": {

View File

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

View File

@@ -3,11 +3,13 @@
/* eslint no-continue: 0 */
/* eslint no-lonely-if: 0 */
/* eslint class-methods-use-this: 0 */
/* eslint camelcase: 0 */
import React from 'react';
import PropTypes from 'prop-types';
export default (options = {
searchFormatted: false
searchFormatted: false,
onColumnMatch: null
}) => (
_,
isRemoteSearch,
@@ -35,7 +37,17 @@ export default (options = {
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 (isRemoteSearch()) {
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) {
const { data, columns } = props;
const searchText = props.searchText.toLowerCase();
@@ -82,11 +84,22 @@ export default (options = {
} else if (column.filterValue) {
targetValue = column.filterValue(targetValue, row);
}
if (targetValue !== null && typeof targetValue !== 'undefined') {
targetValue = targetValue.toString().toLowerCase();
if (targetValue.indexOf(searchText) > -1) {
if (options.onColumnMatch) {
if (options.onColumnMatch({
searchText,
value: targetValue,
column,
row
})) {
return true;
}
} else {
if (targetValue !== null && typeof targetValue !== 'undefined') {
targetValue = targetValue.toString().toLowerCase();
if (targetValue.indexOf(searchText) > -1) {
return true;
}
}
}
}
return false;

View File

@@ -1,6 +1,6 @@
{
"name": "react-bootstrap-table-next",
"version": "3.1.4",
"version": "3.3.1",
"description": "Next generation of react-bootstrap-table",
"main": "./lib/index.js",
"repository": {

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint arrow-body-style: 0 */
import React, { Component } from 'react';
@@ -5,6 +6,7 @@ import PropTypes from 'prop-types';
import cs from 'classnames';
import Header from './header';
import Filters from './filters';
import Caption from './caption';
import Body from './body';
import Footer from './footer';
@@ -18,7 +20,7 @@ class BootstrapTable extends PropsBaseResolver(Component) {
this.validateProps();
}
componentWillReceiveProps(nextProps) {
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.onDataSizeChange && !nextProps.pagination) {
if (nextProps.data.length !== this.props.data.length) {
nextProps.onDataSizeChange({ dataSize: nextProps.data.length });
@@ -64,7 +66,8 @@ class BootstrapTable extends PropsBaseResolver(Component) {
rowEvents,
selectRow,
expandRow,
cellEdit
cellEdit,
filterPosition
} = this.props;
const tableWrapperClass = cs('react-bootstrap-table', wrapperClasses);
@@ -76,6 +79,8 @@ class BootstrapTable extends PropsBaseResolver(Component) {
[bootstrap4 ? 'table-sm' : 'table-condensed']: condensed
}, classes);
const hasFilters = columns.some(col => col.filter || col.filterRenderer);
const hasFooter = _.filter(columns, col => _.has(col, 'footer')).length > 0;
const tableCaption = (caption && <Caption>{ caption }</Caption>);
@@ -91,10 +96,23 @@ class BootstrapTable extends PropsBaseResolver(Component) {
sortOrder={ this.props.sortOrder }
onSort={ this.props.onSort }
onFilter={ this.props.onFilter }
currFilters={ this.props.currFilters }
onExternalFilter={ this.props.onExternalFilter }
selectRow={ selectRow }
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 }
/>
)}
<Body
data={ this.getData() }
keyField={ keyField }
@@ -133,7 +151,7 @@ BootstrapTable.propTypes = {
remote: PropTypes.oneOfType([PropTypes.bool, PropTypes.shape({
pagination: PropTypes.bool
})]),
noDataIndication: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
noDataIndication: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
striped: PropTypes.bool,
bordered: PropTypes.bool,
hover: PropTypes.bool,
@@ -164,6 +182,8 @@ BootstrapTable.propTypes = {
style: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
classes: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
nonSelectable: PropTypes.array,
nonSelectableStyle: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
nonSelectableClasses: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
bgColor: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
hideSelectColumn: PropTypes.bool,
selectionRenderer: PropTypes.func,
@@ -189,12 +209,20 @@ BootstrapTable.propTypes = {
expandColumnPosition: PropTypes.oneOf([
Const.INDICATOR_POSITION_LEFT,
Const.INDICATOR_POSITION_RIGHT
])
]),
className: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
parentClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.func])
}),
rowStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
rowEvents: PropTypes.object,
rowClasses: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
headerClasses: PropTypes.string,
filtersClasses: PropTypes.string,
filterPosition: PropTypes.oneOf([
Const.FILTERS_POSITION_TOP,
Const.FILTERS_POSITION_INLINE,
Const.FILTERS_POSITION_BOTTOM
]),
footerClasses: PropTypes.string,
defaultSorted: PropTypes.arrayOf(PropTypes.shape({
dataField: PropTypes.string.isRequired,
@@ -236,7 +264,8 @@ BootstrapTable.defaultProps = {
cellEdit: {
mode: null,
nonEditableRows: []
}
},
filterPosition: Const.FILTERS_POSITION_INLINE
};
export default BootstrapTable;

View File

@@ -1,3 +1,5 @@
import _ from './utils';
const events = [
'onClick',
'onDoubleClick',
@@ -15,15 +17,15 @@ export default ExtendBase =>
createDefaultEventHandler(cb) {
return (e) => {
const { column, columnIndex } = this.props;
cb(e, column, columnIndex);
const { column, columnIndex, index } = this.props;
cb(e, column, typeof columnIndex !== 'undefined' ? columnIndex : index);
};
}
delegate(attrs = {}) {
const newAttrs = { ...attrs };
Object.keys(attrs).forEach((attr) => {
if (events.includes(attr)) {
if (_.contains(events, attr)) {
newAttrs[attr] = this.createDefaultEventHandler(attrs[attr]);
}
});

View File

@@ -28,6 +28,7 @@ class Cell extends eventDelegater(Component) {
shouldUpdate =
(nextProps.column.formatter ? !_.isEqual(this.props.row, nextProps.row) : false) ||
this.props.column.hidden !== nextProps.column.hidden ||
this.props.column.isDummyField !== nextProps.column.isDummyField ||
this.props.rowIndex !== nextProps.rowIndex ||
this.props.columnIndex !== nextProps.columnIndex ||
this.props.className !== nextProps.className ||

View File

@@ -8,5 +8,12 @@ export default {
CHECKBOX_STATUS_INDETERMINATE: 'indeterminate',
CHECKBOX_STATUS_UNCHECKED: 'unchecked',
INDICATOR_POSITION_LEFT: 'left',
INDICATOR_POSITION_RIGHT: 'right'
INDICATOR_POSITION_RIGHT: 'right',
TYPE_STRING: 'string',
TYPE_NUMBER: 'number',
TYPE_BOOLEAN: 'bool',
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 PropTypes from 'prop-types';
@@ -12,10 +13,6 @@ export default () => {
state = { data: this.props.data };
componentWillReceiveProps(nextProps) {
this.setState(() => ({ data: nextProps.data }));
}
getData = (filterProps, searchProps, sortProps, paginationProps) => {
if (paginationProps) return paginationProps.data;
else if (sortProps) return sortProps.data;
@@ -24,6 +21,10 @@ export default () => {
return this.props.data;
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState(() => ({ data: nextProps.data }));
}
render() {
return (
<DataContext.Provider

View File

@@ -1,3 +1,4 @@
/* eslint camelcase: 0 */
/* eslint no-return-assign: 0 */
/* eslint no-param-reassign: 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) {
this.PaginationContext = null;
}
@@ -91,6 +92,13 @@ const withContext = Base =>
this.PaginationContext = nextProps.pagination.createContext(
this.isRemotePagination, this.handleRemotePageChange);
}
if (!nextProps.cellEdit && this.props.cellEdit) {
this.CellEditContext = null;
}
if (nextProps.cellEdit && !this.props.cellEdit) {
this.CellEditContext = nextProps.cellEdit.createContext(
_, dataOperator, this.isRemoteCellEdit, this.handleRemoteCellChange);
}
}
renderBase() {

View File

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

View File

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

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,70 @@
/* eslint react/require-default-props: 0 */
import React from 'react';
import PropTypes from 'prop-types';
import FiltersCell from './filters-cell';
import Const from './const';
const Filters = (props) => {
const {
columns,
onFilter,
currFilters,
filterPosition,
onExternalFilter,
className
} = props;
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 (
<tbody
className={ className }
style={ {
display:
filterPosition === Const.FILTERS_POSITION_TOP
? 'table-header-group'
: 'table-footer-group'
} }
>
<tr>{filterColumns}</tr>
</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
};
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 _ from './utils';
import eventDelegater from './cell-event-delegater';
const FooterCell = (props) => {
const { index, column, columnData } = props;
class FooterCell extends eventDelegater(React.Component) {
render() {
const { index, column, columnData } = this.props;
const {
footer,
footerTitle,
footerAlign,
footerFormatter,
footerEvents,
footerClasses,
footerStyle,
footerAttrs
} = column;
const {
footer,
footerTitle,
footerAlign,
footerFormatter,
footerEvents,
footerClasses,
footerStyle,
footerAttrs
} = column;
const cellAttrs = {
...(_.isFunction(footerAttrs) ? footerAttrs(column, index) : footerAttrs),
...footerEvents
};
const delegateEvents = this.delegate(footerEvents);
const cellAttrs = {
...(_.isFunction(footerAttrs) ? footerAttrs(column, index) : footerAttrs),
...delegateEvents
};
let text = '';
if (_.isString(footer)) {
text = footer;
} else if (_.isFunction(footer)) {
text = footer(columnData, column, index);
let text = '';
if (_.isString(footer)) {
text = footer;
} 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 = {
columnData: PropTypes.array,

View File

@@ -7,116 +7,142 @@ import Const from './const';
import SortSymbol from './sort/symbol';
import SortCaret from './sort/caret';
import _ from './utils';
import eventDelegater from './cell-event-delegater';
const HeaderCell = (props) => {
const {
column,
index,
onSort,
sorting,
sortOrder,
isLastSorting,
onFilter,
onExternalFilter
} = props;
class HeaderCell extends eventDelegater(React.Component) {
render() {
const {
column,
index,
onSort,
sorting,
sortOrder,
isLastSorting,
onFilter,
currFilters,
filterPosition,
onExternalFilter
} = this.props;
const {
text,
sort,
sortCaret,
filter,
filterRenderer,
headerTitle,
headerAlign,
headerFormatter,
headerEvents,
headerClasses,
headerStyle,
headerAttrs,
headerSortingClasses,
headerSortingStyle
} = column;
const {
text,
sort,
sortCaret,
filter,
filterRenderer,
headerTitle,
headerAlign,
headerFormatter,
headerEvents,
headerClasses,
headerStyle,
headerAttrs,
headerSortingClasses,
headerSortingStyle
} = column;
const cellAttrs = {
..._.isFunction(headerAttrs) ? headerAttrs(column, index) : headerAttrs,
...headerEvents,
tabIndex: 0
};
const delegateEvents = this.delegate(headerEvents);
let sortSymbol;
let filterElm;
let cellStyle = {};
let cellClasses = _.isFunction(headerClasses) ? headerClasses(column, index) : headerClasses;
const customAttrs = _.isFunction(headerAttrs)
? headerAttrs(column, index)
: (headerAttrs || {});
if (headerStyle) {
cellStyle = _.isFunction(headerStyle) ? headerStyle(column, index) : headerStyle;
cellStyle = cellStyle ? { ...cellStyle } : cellStyle;
}
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);
const cellAttrs = {
...customAttrs,
...delegateEvents,
tabIndex: _.isDefined(customAttrs.tabIndex) ? customAttrs.tabIndex : 0
};
cellAttrs.className = cs(cellAttrs.className, 'sortable');
if (sorting) {
sortSymbol = sortCaret ? sortCaret(sortOrder, column) : <SortCaret order={ sortOrder } />;
let sortSymbol;
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.
cellClasses = cs(
cellClasses,
_.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 (headerStyle) {
cellStyle = _.isFunction(headerStyle) ? headerStyle(column, index) : headerStyle;
cellStyle = cellStyle ? { ...cellStyle } : cellStyle;
}
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 = sortCaret ? sortCaret(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 = sortCaret ? sortCaret(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 } 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 = {
column: PropTypes.shape({
dataField: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
type: PropTypes.oneOf([
Const.TYPE_STRING,
Const.TYPE_NUMBER,
Const.TYPE_BOOLEAN,
Const.TYPE_DATE
]),
isDummyField: PropTypes.bool,
hidden: PropTypes.bool,
headerFormatter: PropTypes.func,
@@ -147,7 +173,8 @@ HeaderCell.propTypes = {
validator: PropTypes.func,
filter: PropTypes.object,
filterRenderer: PropTypes.func,
filterValue: PropTypes.func
filterValue: PropTypes.func,
searchable: PropTypes.bool
}).isRequired,
index: PropTypes.number.isRequired,
onSort: PropTypes.func,
@@ -156,6 +183,9 @@ HeaderCell.propTypes = {
sortCaret: PropTypes.func,
isLastSorting: PropTypes.bool,
onFilter: PropTypes.func,
filterPosition: PropTypes.oneOf([Const.FILTERS_POSITION_INLINE,
Const.FILTERS_POSITION_BOTTOM, Const.FILTERS_POSITION_TOP]),
currFilters: PropTypes.object,
onExternalFilter: PropTypes.func
};

View File

@@ -18,8 +18,10 @@ const Header = (props) => {
sortField,
sortOrder,
selectRow,
expandRow,
currFilters,
onExternalFilter,
expandRow
filterPosition
} = props;
let SelectionHeaderCellComp = () => null;
@@ -49,10 +51,12 @@ const Header = (props) => {
column={ column }
onSort={ onSort }
sorting={ currSort }
onFilter={ onFilter }
onExternalFilter={ onExternalFilter }
sortOrder={ sortOrder }
isLastSorting={ isLastSorting }
onFilter={ onFilter }
currFilters={ currFilters }
onExternalFilter={ onExternalFilter }
filterPosition={ filterPosition }
/>);
})
];
@@ -89,9 +93,15 @@ Header.propTypes = {
sortField: PropTypes.string,
sortOrder: PropTypes.string,
selectRow: PropTypes.object,
currFilters: PropTypes.object,
onExternalFilter: PropTypes.func,
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;

View File

@@ -22,7 +22,7 @@ export default ExtendBase =>
if (!hiddenRows || hiddenRows.length === 0) return data;
return data.filter((row) => {
const key = _.get(row, keyField);
return !hiddenRows.includes(key);
return !_.contains(hiddenRows, key);
});
}
};

View File

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

View File

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

View File

@@ -1,10 +1,11 @@
import cs from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { CSSTransition } from 'react-transition-group';
const ExpandRow = ({ children, expanded, onClosed, ...rest }) => (
const ExpandRow = ({ children, expanded, onClosed, className, ...rest }) => (
<tr>
<td className="reset-expansion-style" { ...rest }>
<td className={ cs('reset-expansion-style', className) } { ...rest }>
<CSSTransition
appear
in={ expanded }
@@ -25,13 +26,15 @@ const ExpandRow = ({ children, expanded, onClosed, ...rest }) => (
ExpandRow.propTypes = {
children: PropTypes.node,
expanded: PropTypes.bool,
onClosed: PropTypes.func
onClosed: PropTypes.func,
className: PropTypes.string
};
ExpandRow.defaultProps = {
children: null,
expanded: false,
onClosed: null
onClosed: null,
className: ''
};
export default ExpandRow;

View File

@@ -1,15 +1,29 @@
/* eslint react/prop-types: 0 */
import React from 'react';
import cs from 'classnames';
import ExpandRow from './expand-row';
import _ from '../utils';
import ExpansionContext from '../contexts/row-expand-context';
export default (Component) => {
const renderWithExpansion = (props, expandRow) => {
let parentClassName = '';
let className = '';
const key = props.value;
const expanded = expandRow.expanded.includes(key);
const isClosing = expandRow.isClosing.includes(key);
const expandable = !expandRow.nonExpandable || !expandRow.nonExpandable.includes(key);
const expanded = _.contains(expandRow.expanded, key);
const isClosing = _.contains(expandRow.isClosing, key);
const expandable = !expandRow.nonExpandable || !_.contains(expandRow.nonExpandable, key);
if (expanded) {
parentClassName = _.isFunction(expandRow.parentClassName) ?
expandRow.parentClassName(expanded, props.row, props.rowIndex) :
(expandRow.parentClassName || '');
className = _.isFunction(expandRow.className) ?
expandRow.className(expanded, props.row, props.rowIndex) :
(expandRow.className || '');
}
return [
<Component
{ ...props }
@@ -17,14 +31,16 @@ export default (Component) => {
expanded={ expanded }
expandable={ expandable }
expandRow={ { ...expandRow } }
className={ cs(props.className, parentClassName) }
/>,
expanded || isClosing ? <ExpandRow
key={ `${key}-expanding` }
colSpan={ props.visibleColumnSize }
expanded={ expanded }
onClosed={ () => expandRow.onClosed(key) }
className={ className }
>
{ expandRow.renderer(props.row) }
{ expandRow.renderer(props.row, props.rowIndex) }
</ExpandRow> : null
];
};

View File

@@ -7,8 +7,9 @@ import SelectionContext from '../contexts/selection-context';
export default (Component) => {
const renderWithSelection = (props, selectRow) => {
const key = props.value;
const selected = selectRow.selected.includes(key);
const selectable = !selectRow.nonSelectable || !selectRow.nonSelectable.includes(key);
const selected = _.contains(selectRow.selected, key);
const selectable = !selectRow.nonSelectable || !_.contains(selectRow.nonSelectable, key);
const notSelectable = _.contains(selectRow.nonSelectable, key);
let {
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 (
<Component
{ ...props }

View File

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

View File

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

View File

@@ -35,12 +35,13 @@ export default class RowAggregator extends shouldUpdater(eventDelegater(React.Co
this.props.expanded !== nextProps.expanded ||
this.props.expandable !== nextProps.expandable ||
this.props.selectable !== nextProps.selectable ||
this.props.selectRow.hideSelectColumn !== nextProps.selectRow.hideSelectColumn ||
this.shouldUpdatedBySelfProps(nextProps)
) {
this.shouldUpdateRowContent = this.shouldUpdateChild(nextProps);
this.shouldUpdateRowContent = this.shouldRowContentUpdate(nextProps);
return true;
}
this.shouldUpdateRowContent = this.shouldUpdateChild(nextProps);
this.shouldUpdateRowContent = this.shouldRowContentUpdate(nextProps);
return this.shouldUpdateRowContent;
}

View File

@@ -74,7 +74,7 @@ export default ExtendBase =>
delegate(attrs = {}) {
const newAttrs = { ...attrs };
Object.keys(attrs).forEach((attr) => {
if (events.includes(attr)) {
if (_.contains(events, attr)) {
newAttrs[attr] = this.createDefaultEventHandler(attrs[attr]);
}
});

View File

@@ -48,4 +48,9 @@ export default ExtendBase =>
return this.shouldUpdateByCellEditing(nextProps) ||
this.shouldUpdatedByNormalProps(nextProps);
}
shouldRowContentUpdate(nextProps) {
return this.shouldUpdateChild(nextProps) ||
this.shouldUpdateByColumnsForSimpleCheck(nextProps);
}
};

View File

@@ -15,8 +15,7 @@ class SimpleRow extends shouldUpdater(eventDelegater(Component)) {
shouldComponentUpdate(nextProps) {
this.shouldUpdateRowContent = false;
this.shouldUpdateRowContent =
this.shouldUpdateChild(nextProps) || this.shouldUpdateByColumnsForSimpleCheck(nextProps);
this.shouldUpdateRowContent = this.shouldRowContentUpdate(nextProps);
if (this.shouldUpdateRowContent) return true;
return this.shouldUpdatedBySelfProps(nextProps);

View File

@@ -20,7 +20,7 @@ export const expandableKeys = (data, keyField, skips = []) => {
return data.map(row => _.get(row, keyField));
}
return data
.filter(row => !skips.includes(_.get(row, keyField)))
.filter(row => !_.contains(skips, _.get(row, keyField)))
.map(row => _.get(row, keyField));
};

View File

@@ -3,11 +3,13 @@ import * as selection from './selection';
import * as expand from './expand';
import * as mutate from './mutate';
import * as sort from './sort';
import * as type from './type';
export default {
...rows,
...selection,
...expand,
...mutate,
...sort
...sort,
...type
};

View File

@@ -2,14 +2,14 @@ import _ from '../utils';
import { getRowByRowId } from './rows';
export const getSelectionSummary = (
data,
data = [],
keyField,
selected = []
) => {
let allRowsSelected = data.length > 0;
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) {
const curr = rowKeys[i];
if (typeof selected.find(x => x === curr) === 'undefined') {
@@ -24,12 +24,12 @@ export const getSelectionSummary = (
};
};
export const selectableKeys = (data, keyField, skips = []) => {
export const selectableKeys = (data = [], keyField, skips = []) => {
if (skips.length === 0) {
return data.map(row => _.get(row, keyField));
}
return data
.filter(row => !skips.includes(_.get(row, keyField)))
.filter(row => !_.contains(skips, _.get(row, keyField)))
.map(row => _.get(row, keyField));
};
@@ -37,9 +37,9 @@ export const unSelectableKeys = (selected, skips = []) => {
if (skips.length === 0) {
return [];
}
return selected.filter(x => skips.includes(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);

View File

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

View File

@@ -0,0 +1,18 @@
import Const from '../const';
export const typeConvert = (type, value) => {
if (type === Const.TYPE_STRING) {
return String(value);
} else if (type === Const.TYPE_NUMBER) {
return Number(value);
} else if (type === Const.TYPE_BOOLEAN) {
if (typeof value === 'boolean') {
return value;
}
return value === 'true';
} else if (type === Const.TYPE_DATE) {
return new Date(value);
}
return value;
};

View File

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

Some files were not shown because too many files have changed in this diff Show More