Compare commits

...
Author SHA1 Message Date
Tanner Linsley b3771502f8 v7.0.0-rc.11 2019-12-17 20:50:59 -07:00
Tanner Linsley 0df8cc5088 Update useFlexLayout.md 2019-12-17 20:46:03 -07:00
Tanner Linsley 7cebab7fb6 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-17 20:44:48 -07:00
Tanner Linsley 717ea7b211 Update Docs 2019-12-17 20:44:33 -07:00
size-plugin[bot]andGitHub 823d93946b 💁🏿‍♂️ 🚵‍♂️ update sizes-es.json 👍 2019-12-18 03:43:47 +00:00
size-plugin[bot]andGitHub b01749c5c7 🕴️ 🍀 update sizes-cjs.json 👍 2019-12-18 03:43:46 +00:00
Tanner Linsley b48cddb92b Add back useFlexLayout and full-width-resizable-table example 2019-12-17 20:41:28 -07:00
Tanner Linsley f48ef14975 Fix reset to use initial state, then fall back to default state 2019-12-17 20:40:34 -07:00
Tanner Linsley eeee14830d Update Changelog 2019-12-17 19:32:07 -07:00
Tanner Linsley f2776d0005 Fix getcolumnsHooks 2019-12-17 19:31:50 -07:00
Tanner Linsley ee18cf4b89 Add streaming rows snapshot 2019-12-17 19:31:09 -07:00
Chris NorwoodandTanner Linsley 632ea28c4b Update to use React.Fragment spread with row props (#1781) 2019-12-13 18:08:01 -07:00
Tanner LinsleyandGitHub 506a22062e Update README.md 2019-12-13 13:52:59 -07:00
size-plugin[bot]andGitHub 9e81e44da3 ☺️ 👨🏿‍🦳 update sizes-es.json 👍 2019-12-13 08:02:58 +00:00
size-plugin[bot]andGitHub acd6ac5d14 🤹🏽 🏋🏾 update sizes-es.json 👍 2019-12-13 08:00:27 +00:00
size-plugin[bot]andGitHub 78634585e7 🍒 👨🏼‍🍳 update sizes-es.json 👍 2019-12-13 07:55:23 +00:00
Tanner Linsley c8d2180e5b Create sandbox.config.json 2019-12-13 00:52:32 -07:00
Tanner Linsley 0575c1b36d Update examples.md 2019-12-13 00:50:11 -07:00
Tanner Linsley 96a185af59 v7.0.0-rc.10 2019-12-13 00:45:01 -07:00
Tanner Linsley 8c5f5084d2 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-13 00:44:18 -07:00
Tanner Linsley bca95b0928 Fix selection examples 2019-12-13 00:43:54 -07:00
Tanner Linsley 4143208334 Fix prefilteredRows 2019-12-13 00:41:10 -07:00
size-plugin[bot]andGitHub a3fb80fb81 🧝🏻 👷🏽‍♀️ update sizes-es.json 👍 2019-12-13 07:28:24 +00:00
size-plugin[bot]andGitHub 77f7eb689d 🇲🇩 🐏 update sizes-cjs.json 👍 2019-12-13 07:28:23 +00:00
Tanner Linsley d421cb52c5 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-13 00:26:06 -07:00
Tanner Linsley 81dcfd8dec Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-13 00:25:27 -07:00
Tanner Linsley 9fa1396f26 Mucho updates 2019-12-13 00:22:30 -07:00
Jason LawandTanner Linsley 0de4f69f14 Fix useRowSelect shouldExist (#1774) 2019-12-13 00:16:30 -07:00
size-plugin[bot]andGitHub dafd1a1972 😵 📆 update sizes-cjs.json 👍 2019-12-12 15:55:20 +00:00
size-plugin[bot]andGitHub cd5f7e6968 👩🏼‍🎓 👸🏼 update sizes-es.json 👍 2019-12-12 15:55:19 +00:00
Peng XiaoandTanner Linsley 32ae1a52e4 fix: render components should include memo/forwardRef (#1764) 2019-12-12 08:51:37 -07:00
Yarin BenadoandTanner Linsley 1509fc0438 Rename manualSorting to manualSortBy to reflect API changes (#1770) 2019-12-12 08:50:05 -07:00
Tanner LinsleyandGitHub 048f118279 Update README.md 2019-12-11 16:31:33 -07:00
Tanner LinsleyandGitHub e661d90d48 Update README.md 2019-12-11 15:43:57 -07:00
size-plugin[bot]andGitHub a9c04ca3dc 🩳 👨🏼 update sizes-es.json 👍 2019-12-11 06:08:38 +00:00
size-plugin[bot]andGitHub 1f18260a70 ✉️ 🇧🇫 update sizes-cjs.json 👍 2019-12-11 06:08:37 +00:00
Tanner Linsley 3109ca4d37 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 23:06:52 -07:00
Tanner Linsley b517ee13d5 v7.0.0-rc.9 2019-12-10 23:05:57 -07:00
Tanner Linsley ddfa0fa227 Death of the path, fix some hooks, fix selectedRows
- Fixed an issue where dependency hooks were not being reduced properly, thus the table would rerender unnecessarily
- Renamed `toggleRowSelectedAll` to `toggleAllRowsSelected`. Duh...
- Added an `indeterminate` boolean prop to the default props for row selection toggle prop getters
- Renamed `selectedRowPaths` to `selectedRowIds`, which also no longer contains paths, but row IDs
- Grouped or nested row selection actions and state are now derived, instead of tracked in state.
- Rows now have a new property called `id`, which existed before and was derived from the `getRowId` option
- Rows now also have an `isSomeSelected` prop when using the `useRowSelect` hook, which denotes that at least one subRow is selected (if applicable)
- Rows' `path` property has been deprecated in favor of `id`
- Expanded state is now tracked with row IDs instead of paths
- RowState is now tracked with row IDs instead of paths
- `toggleExpandedByPath` has been renamed to `toggleExpandedById`, and thus accepts a row ID now, instead of a row path
2019-12-10 23:04:34 -07:00
size-plugin[bot]andGitHub 63c6a56e38 🇪🇸 🏄🏾‍♀️ update sizes-es.json 👍 2019-12-10 23:36:27 +00:00
size-plugin[bot]andGitHub 213caf6544 👦 📎 update sizes-cjs.json 👍 2019-12-10 23:36:25 +00:00
Tanner Linsley 42b78d52ca v7.0.0-rc.8 2019-12-10 16:35:19 -07:00
Tanner Linsley 68fd89af3c Fix props clobbering
Fixes #1755
2019-12-10 16:34:23 -07:00
Tanner Linsley 0c43e19091 Fix useResizeColumns bug 2019-12-10 14:58:31 -07:00
size-plugin[bot]andGitHub 08bb50ae48 🧑🏻‍🤝‍🧑🏻 🔔 update sizes-es.json 👍 2019-12-10 19:44:09 +00:00
size-plugin[bot]andGitHub 0fcc9e608c 🇰🇪 🍐 update sizes-cjs.json 👍 2019-12-10 19:44:08 +00:00
Tanner Linsley 15125f9326 Update useColumnVisibility.js 2019-12-10 12:42:19 -07:00
Tanner Linsley b8701f260a Update CHANGELOG.md 2019-12-10 12:33:44 -07:00
Tanner Linsley 70bdd272e5 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 11:59:39 -07:00
size-plugin[bot]andGitHub 5ad648d9da 🇧🇸 👮🏽‍♂️ update sizes-es.json 👍 2019-12-10 18:58:59 +00:00
size-plugin[bot]andGitHub 117dc54439 💻 🙍🏾‍♀️ update sizes-cjs.json 👍 2019-12-10 18:58:58 +00:00
Tanner Linsley d8f0174d80 v7.0.0-rc.7 2019-12-10 11:57:54 -07:00
Tanner Linsley cf9517fe7a Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 11:57:21 -07:00
Tanner Linsley e1fd921f07 Add useFinalInstance plugin hook 2019-12-10 11:56:41 -07:00
dependabot[bot]andTanner Linsley 7222c1cb2b Bump eslint-utils from 1.4.0 to 1.4.3 in /examples/row-selection (#1754)
Bumps [eslint-utils](https://github.com/mysticatea/eslint-utils) from 1.4.0 to 1.4.3.
- [Release notes](https://github.com/mysticatea/eslint-utils/releases)
- [Commits](https://github.com/mysticatea/eslint-utils/compare/v1.4.0...v1.4.3)

Signed-off-by: dependabot[bot] <support@github.com>
2019-12-10 11:51:39 -07:00
size-plugin[bot]andGitHub e984934e92 👩🏽‍⚖️ 🕵🏾‍♀️ update sizes-es.json 👍 2019-12-10 18:44:23 +00:00
size-plugin[bot]andGitHub 938bdd9885 🧏🏾 ✡️ update sizes-cjs.json 👍 2019-12-10 18:44:22 +00:00
Tanner Linsley 88a0d86d60 Update .size-snapshot.json 2019-12-10 11:42:31 -07:00
Tanner Linsley 690190081f Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 11:37:07 -07:00
Tanner Linsley 4a3311035d Added/updated hooks reorganization of hooks, new hook rules
- The exported (but undocumented) `applyHooks` function has been deprecated. Please use either `reduceHooks` or `loopHooks` utilities in your custom plugins now.
- The exported (but undocumented) `applyPropHooks` function has been deprecated. Please use the `makePropGetter` utility in your custom plugins now.
- Added the `reduceHooks` exported utility which is used to reduce a value through a collection of hooks. Each hook must return a value (mutation is discouraged)
- Added the `loopHooks` exported utility which is used to loop over a collection of hooks. Hooks are not allowed to return a value (mutation is encouraged)
- Prop-getter hook functions now support returning an array (in addition to the typical object of props). When an array is returned, each item in the array is smart-merged into a new props object (meaning it will intelligently compose and override styles and className)
- Added the `makePropGetter` exported utility which is used to create prop getters from a prop getter hook.
- Prop-getter function supplied to the table have 2 new overloaded options (in addition to the typical object of props):
  - `Function(props, instance, ...row/col/context) => Array<props> | props` - If a function is passed to a prop getter function, it will receive the previous props, the table instance, and potentially more context arguments. It is then be expected to return either an array of new props (to be smart-merged with styles and classes, the latest values taking priority over the previous values) or a props object (which will replace all previous props)
  - `Array<props>` - If an array is passed to a prop getter function, each prop object in the array will be smart-merged with styles and classes into the props from previous hooks (with the latest values taking priority over the previous values).
- Extracted default hooks into separate file.
- Added the `useOptions` plugin hook, which allows a plugin to reduce/modify the initial options being passed to the table
- Converted almost all usages of `instanceRef.current` to use `useGetLatest(instanceRef.current)` to help with avoiding memory leaks and to be more terse.
- Converted all previous prop-getter definitions to use the new `makePropGetter`
- Reorganized plugin hooks to declare as many hooks in the main plugin function as opposed to in the `useInstance` hook.
- Changed the `useInstanceBeforeDimensions` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to discourage mutation of the instance)
- Changed the `useInstance` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to discourage mutation of the instance)
- Change the `prepareRow` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to discourage mutation of the row)
2019-12-10 11:35:05 -07:00
size-plugin[bot]andGitHub a73ee145b3 💍 ️ update sizes-cjs.json 👍 2019-12-10 13:42:08 +00:00
size-plugin[bot]andGitHub b0d2044e22 🤫 💪🏻 update sizes-es.json 👍 2019-12-10 13:42:07 +00:00
Jakob Hjelmer NielsenandTanner Linsley ccc89379da .add touch events to useResizeColumns (#1748)
.add onTouchStart to mergeProps
.add touch-action css to resizer
.mod increase resizer width or it is very hard to activate using touch devices
2019-12-10 06:39:02 -07:00
Tanner Linsley 9563dae006 Update README.md 2019-12-09 10:51:07 -07:00
Tanner Linsley d35d190708 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-09 10:51:05 -07:00
Tanner Linsley 614f40f47d Fix controlled pagination example 2019-12-09 10:12:36 -07:00
size-plugin[bot]andGitHub 5846c86605 👨‍💻 🛹 update sizes-es.json 👍 2019-12-09 17:02:19 +00:00
size-plugin[bot]andGitHub c5fb154d9b ⛹🏻‍♂️ 🏋🏼‍♀️ update sizes-cjs.json 👍 2019-12-09 17:02:18 +00:00
Tanner Linsley 5e6952db93 v7.0.0-rc.6 2019-12-09 09:53:29 -07:00
Tanner Linsley ac43ef2e38 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-09 09:52:50 -07:00
Tanner Linsley 9de699bfd3 Add/rename a few hooks, fix useColumnVisibility header deps
- The `columnsBeforeHeaderGroups` and `columnsBeforeHeaderGroupsDeps` hooks have been renamed to `flatColumns` and `flatColumnsDeps` respectively, which better reflects what they are used for, rather than their order, which can remain implicit.
- Added `headerGroups` and `headerGroupDeps` hooks, which, similar to `flatColumns`, allow you to decorate (and trigger) the memoized header group generation.
- Added `columns` and `columnsDeps` hooks, which, similar to `flatColumns` and `headerGroups`, allow you to decorate (and trigger) the memoized column generation/decoration.
- The new hook order is as follows: `columns/columnsDeps` => `flatColumns/flatColumnsDeps` => `headerGroups/headerGroupsDeps`
- `useColumnVisibility` now uses the new `headerGroupsDeps` hook to trigger header group regeneration when visibility changes
2019-12-09 09:52:27 -07:00
size-plugin[bot]andGitHub 38d82a0397 📘 🍫 update sizes-es.json 👍 2019-12-09 02:40:17 +00:00
size-plugin[bot]andGitHub 863bf50206 🍊 👨🏾‍🎨 update sizes-cjs.json 👍 2019-12-09 02:40:16 +00:00
Tanner Linsley 492ba8a4f9 Update Changelog 2019-12-08 19:35:55 -07:00
Tanner Linsley e0ad323bd8 v7.0.0-rc.5 2019-12-08 19:32:45 -07:00
Tanner Linsley c1e4fb8956 v7.0.0-rc.4 2019-12-08 19:26:49 -07:00
Bart NagelandTanner Linsley 1ac1d99f23 Fix link in documentation (#1733) 2019-12-06 21:51:34 -07:00
size-plugin[bot]andGitHub e5b991751a 🏊🏿‍♂️ 🧜🏻‍♂️ update sizes-cjs.json 👍 2019-12-07 03:49:50 +00:00
Bart NagelandTanner Linsley 8dc6559e64 Fix row.toggleExpanded(bool) (#1732)
The wrong variable was being checked against `undefined`, so the row was
always being toggled, rather than taking the parameter into account.
2019-12-06 20:39:45 -07:00
dependabot[bot]andTanner Linsley 2955335df1 Bump eslint-utils from 1.4.0 to 1.4.3 in /examples/grouping (#1730)
Bumps [eslint-utils](https://github.com/mysticatea/eslint-utils) from 1.4.0 to 1.4.3.
- [Release notes](https://github.com/mysticatea/eslint-utils/releases)
- [Commits](https://github.com/mysticatea/eslint-utils/compare/v1.4.0...v1.4.3)

Signed-off-by: dependabot[bot] <support@github.com>
2019-12-06 16:42:41 -07:00
Tanner Linsley 8c090a734b Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-06 16:36:50 -07:00
Tanner Linsley 439ebad063 Update faq.md 2019-12-06 16:36:17 -07:00
size-plugin[bot]andGitHub 2ef6e13657 🧎🏼 🤳🏽 update sizes-es.json 👍 2019-12-06 23:35:30 +00:00
size-plugin[bot]andGitHub 6338b32bd8 🧝🏽‍♂️ 🇲🇦 update sizes-cjs.json 👍 2019-12-06 23:35:29 +00:00
Tanner Linsley 67544d33ff v7.0.0-rc.3 2019-12-06 16:33:41 -07:00
Tanner Linsley 3fa2cdf388 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-06 16:30:42 -07:00
Tanner Linsley 562a2feaef v7.0.0-rc.2 2019-12-06 16:30:08 -07:00
AlbericoandTanner Linsley 176986a07a docs(docs/api/readme.md): fix to useTable link that was giving 404 (#1726)
In the /docs/api/README.md the useTable link was linking to the file ./usetable.md that doesn't
exist, now it links to ./useTable
2019-12-06 10:25:15 -05:00
size-plugin[bot]andGitHub f824fea2ef 🙍🏿 ♟️ update sizes-es.json 👍 2019-12-06 08:21:02 +00:00
size-plugin[bot]andGitHub ace8f56371 🇦🇪 💨 update sizes-cjs.json 👍 2019-12-06 08:21:01 +00:00
gargrohandTanner Linsley 3d5249b716 [useSortBy] updating missed key rename (#1724) 2019-12-06 03:19:28 -05:00
ggascoigneandTanner Linsley 546cb4e076 put useFilters docs in correct file (#1723) 2019-12-06 01:18:48 -05:00
size-plugin[bot]andGitHub d1677dfebb 🇻🇨 🤰🏻 update sizes-es.json 👍 2019-12-06 04:37:44 +00:00
size-plugin[bot]andGitHub 4868d7835f 😖 💇🏾‍♀️ update sizes-cjs.json 👍 2019-12-06 04:37:43 +00:00
113 changed files with 34546 additions and 2058 deletions
+2 -1
View File
@@ -3,7 +3,8 @@
[
"@babel/preset-env",
{
"modules": false
"modules": false,
"loose": true
}
],
"@babel/react"
+27 -8
View File
@@ -1,20 +1,39 @@
{
"dist/index.js": {
"bundled": 102847,
"minified": 50399,
"gzipped": 12909
"bundled": 107213,
"minified": 49659,
"gzipped": 13264
},
"dist/index.es.js": {
"bundled": 101791,
"minified": 49456,
"gzipped": 12726,
"bundled": 106302,
"minified": 48847,
"gzipped": 13099,
"treeshaked": {
"rollup": {
"code": 78,
"code": 80,
"import_statements": 21
},
"webpack": {
"code": 14193
"code": 8249
}
}
},
"dist\\index.js": {
"bundled": 105386,
"minified": 49565,
"gzipped": 13008
},
"dist\\index.es.js": {
"bundled": 104543,
"minified": 48815,
"gzipped": 12856,
"treeshaked": {
"rollup": {
"code": 80,
"import_statements": 21
},
"webpack": {
"code": 8444
}
}
}
+116 -1
View File
@@ -1,3 +1,118 @@
## 7.0.0-rc.11
- Fixed an issue where plugins using the `columns` hook were not getting decorated properly
- Added back a new rendition of the `useFlexLayout` plugin and accompanying example.
- Fixed all reset actions to use the initial state passed into the table, then fall back to the default initial state for the hook
## 7.0.0-rc.10
- Optimizations made to make accessors, prop getters and other internals much faster. 10x in some cases!
- Fixed docs for `usePagination` to have `pageIndex` and `pageSize` only available on the state object, not the instance
- Added a plugin order restriction to make sure `useResizeColumns` always comes before `useAbsoluteLayout`
- Fixed the `useFinalInstance` hook to not have an empty array as the first meta argument passed.
- Fixed an issue where memoized or ref-forwarded components could not be used as cell renderers
- The `toggleExpandedById` action has been renamed to `toggleExpanded`
- Added the `toggleAllExpanded` action
- Added the `setExpanded` action
- Changed `row.isAggregated` to `row.isGrouped`
- `state.expanded` and `state.selectedRowIds` are now objects (`{[rowId]: Bool}`), not arrays. This should help with mid-to-large size datasets while also being serializable (instead of a Set(), which is not as reliable)
- `state.filters` is now an array of objects (`{id, value}`). Since filters do have order and can be applied incrementally, it should be an array to ensure correct order.
- Moved the `flatColumns` and `flatColumnsDeps` hooks to be after row/data materialization. These hooks can then manipulate the `flatColumns` object after all data has been accessed without triggering row materialization again.
- Added the `row.allCells` property and the `cellColumns` reducer hook to determine which cells to create for each row. These cells are placed into `row.allCells`. The resulting cell array is not meant to be used for display in templating and is only made available for convenience and/or advanced templating.
- Added the `cells` reducer hook to determine which cells from the `row.allCells` array that should be placed into `row.cells`. The resulting cell array is the one that is intended for display in templating.
- Reducers are now passed the actual instance variable, not the instanceRef
- Added the `makeRenderer` utility (also exported)
- Removed `column.groupByBoundary` functionality. If needed, use the `flatColumns` hook to decorate, reorganize or re-order groupBy columns
- Fixed grouped row.id's to be truly unique
## 7.0.0-rc.9
- Fixed an issue where dependency hooks were not being reduced properly, thus the table would rerender unnecessarily
- Renamed `toggleRowSelectedAll` to `toggleAllRowsSelected`. Duh...
- Added an `indeterminate` boolean prop to the default props for row selection toggle prop getters
- Renamed `selectedRowPaths` to `selectedRowIds`, which also no longer contains paths, but row IDs
- Grouped or nested row selection actions and state are now derived, instead of tracked in state.
- Rows now have a new property called `id`, which existed before and was derived from the `getRowId` option
- Rows now also have an `isSomeSelected` prop when using the `useRowSelect` hook, which denotes that at least one subRow is selected (if applicable)
- Rows' `path` property has been deprecated in favor of `id`
- Expanded state is now tracked with row IDs instead of paths
- RowState is now tracked with row IDs instead of paths
- `toggleExpandedByPath` has been renamed to `toggleExpandedById`, and thus accepts a row ID now, instead of a row path
## 7.0.0-rc.8
- Fix an issue where `useResizeColumns` would crash when using the resizer prop getter
- Fix an issue where `useBlockLayout` was clobbering props sent to headers
## 7.0.0-rc.7
Removed:
- `applyHooks` (exported but undocumented) function has been deprecated. Please use either `reduceHooks` or `loopHooks` utilities in your custom plugins now.
- `applyPropHooks` (exported but undocumented) function has been deprecated. Please use the `makePropGetter` utility in your custom plugins now.
Added:
- `reduceHooks` exported utility which is used to reduce a value through a collection of hooks. Each hook must return a value (mutation is discouraged)
- `loopHooks` exported utility which is used to loop over a collection of hooks. Hooks are not allowed to return a value (mutation is encouraged)
- `makePropGetter` exported utility which is used to create prop getters from a prop getter hook.
- `useOptions` plugin hook, which allows a plugin to reduce/modify the initial options being passed to the table
- `useFinalInstance` plugin hook, which allows a plugin access to the final table instance before it is returned to the user.
Modified:
- Prop-getter hook functions now support returning an array (in addition to the typical object of props). When an array is returned, each item in the array is smart-merged into a new props object (meaning it will intelligently compose and override styles and className)
- Prop-getter function supplied to the table have 2 new overloaded options (in addition to the typical object of props):
- `Function(props, instance, ...row/col/context) => Array<props> | props` - If a function is passed to a prop getter function, it will receive the previous props, the table instance, and potentially more context arguments. It is then be expected to return either an array of new props (to be smart-merged with styles and classes, the latest values taking priority over the previous values) or a props object (which will replace all previous props)
- `Array<props>` - If an array is passed to a prop getter function, each prop object in the array will be smart-merged with styles and classes into the props from previous hooks (with the latest values taking priority over the previous values).
- Extracted default hooks into separate file.
- Converted almost all usages of `instanceRef.current` to use `useGetLatest(instanceRef.current)` to help with avoiding memory leaks and to be more terse.
- Converted all previous prop-getter definitions to use the new `makePropGetter`
- Reorganized plugin hooks to declare as many hooks in the main plugin function as opposed to in the `useInstance` hook.
- Changed the `useInstanceBeforeDimensions` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to encourage mutation of the instance)
- Changed the `useInstance` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to encourage mutation of the instance)
- Change the `prepareRow` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to encourage mutation of the row)
## 7.0.0-rc.6
- The `columnsBeforeHeaderGroups` and `columnsBeforeHeaderGroupsDeps` hooks have been renamed to `flatColumns` and `flatColumnsDeps` respectively, which better reflects what they are used for, rather than their order, which can remain implicit.
- Added `headerGroups` and `headerGroupDeps` hooks, which, similar to `flatColumns`, allow you to decorate (and trigger) the memoized header group generation.
- Added `columns` and `columnsDeps` hooks, which, similar to `flatColumns` and `headerGroups`, allow you to decorate (and trigger) the memoized column generation/decoration.
- The new hook order is as follows: `columns/columnsDeps` => `flatColumns/flatColumnsDeps` => `headerGroups/headerGroupsDeps`
- `useColumnVisibility` now uses the new `headerGroupsDeps` hook to trigger header group regeneration when visibility changes
## 7.0.0-rc.5
- Fixed an issue where the exported `useAsyncDebounce` method would crash if its promise throw an error.
## 7.0.0-rc.4
- A maintenance release, purely intended to update the @latest tag (which was overwritten by a v6 publish)
## 7.0.0-rc.3
- Fixed an issue where `column.clearSortBy` would crash
## 7.0.0-rc.2
- `reducerHandlers` has been deprecated in favor of the new `stateReducers` hook.
- The `previousState` and `instanceRef` are now both generally available in state reducers for convenience.
- The global action property `action.instanceRef` has been deprecated.
- The `reducer` option has been renamed to `stateReducer` and in addition to passing a single reducer function now also supports passing an array of reducers
- Renamed `manualSorting` to be `manualSortBy` to be consistent with other naming conventions
- Removed the `getResetPageDeps` option in favor of the new `autoResetPage` option.
- Removed the `getResetFilterDeps` option in favor of the new `autoResetFilters` option.
- Removed the `getResetSortByDeps` option in favor of the new `autoResetSortBy` option.
- Removed the `getResetGroupByDeps` option in favor of the new `autoResetGroupBy` option.
- Removed the `getResetExpandedDeps` option in favor of the new `autoResetExpanded` option.
- Added a new exported utility called `useAsyncDebounce` to aid with external async side-effects.
- A new `useGetLatest` hook is used internally to track latest instances in a less ref-driven and verbose way.
- A new `useMountedLayoutEffect` hooks is now used internally to handle post-mount side-effects, mostly dealing with autoReset functionality
- Plugin hooks are now "consumed" using an internal `useConsumeHookGetter` hook. When they are consumed, they can no longer be manipulated past that point in the table lifecycle. This should help ensure people are using them in a relatively safe order with consistent expectations.
- Drastically "reduced" the reducer logic itself to be easier to understand and to be a stable reference for the life of the table. This change also means that the reducer must no longer be double-run/back-compared by React for changes in closure, thus actions and stateReducers (including user state reducers) will only fire once per action.
- Removed `debug` and related logging. It has been somewhat useful during development, but is now very noisy in the code. We can debug lifecycle and performance as needed from here on out.
- Removed unnecessary exports from `./utils.js` and moved all intentionally exported utilities to a new `./publicUtils.js` file.
## 7.0.0-rc.1
- Minor regex optimizations during row path creation
@@ -27,7 +142,7 @@
## 7.0.0-beta.24
- Changed `selectedRowPaths` to use a `Set()` instead of an array for performance.
- Changed `selectedRowIds` to use a `Set()` instead of an array for performance.
- Removed types and related files from the repo. The community will now maintain types externally on Definitely Typed
## 7.0.0-beta.23
+3 -2
View File
@@ -21,7 +21,7 @@ Enjoy this library? Try them all! [React Query](https://github.com/tannerlinsley
## Features
- Lightweight (4kb - 11kb depending on features and tree-shaking)
- Lightweight (5kb - 12kb+ depending on features used and tree-shaking)
- Headless (100% customizable, Bring-your-own-UI)
- Auto out of the box, fully controllable API
- Sorting (Multi and Stable)
@@ -35,7 +35,6 @@ Enjoy this library? Try them all! [React Query](https://github.com/tannerlinsley
- Resizable
- Server-side/controlled data/state
- Extensible via hook-based plugin system
- <a href="https://medium.com/@tannerlinsley/why-i-wrote-react-table-and-the-problems-it-has-solved-for-nozzle-others-445c4e93d4a8#.axza4ixba" target="\_parent">"Why I wrote React Table and the problems it has solved for Nozzle.io"</a> by Tanner Linsley
## Documentation
@@ -183,6 +182,8 @@ This library is being built and maintained by me, @tannerlinsley and I am always
<li>Robert Tajnšek</li>
<li>Pekka Tapani</li>
<li>Eric Lanehart (@pushred)</li>
<li>Anish P Patel (@anishpatelyaadada)</li>
<li>Alin Porumb (@alinporumb)</li>
</ul>
</td>
<td>
+2 -1
View File
@@ -5,7 +5,7 @@ React Table uses React Hooks both internally and externally for almost all of it
React Table is essentially a compatible collection of **custom React hooks**:
- The primary React Table hook
- [`useTable`](./usetable.md)
- [`useTable`](./useTable.md)
- Plugin Hooks
- Core Plugin Hooks
- [`useGroupBy`](./useGroupBy.md)
@@ -20,6 +20,7 @@ React Table is essentially a compatible collection of **custom React hooks**:
- Layout Hooks
- [`useBlockLayout`](./useBlockLayout.md)
- [`useAbsoluteLayout`](./useAbsoluteLayout.md)
- [`useFlexLayout`](./useFlexLayout.md)
- [`useResizeColumns`](./useResizeColumns.md)
- 3rd Party Plugin Hooks
- Want your custom plugin hook listed here? [Submit a PR!](https://github.com/tannerlinsley/react-table/compare)
+6
View File
@@ -25,6 +25,12 @@
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows cells
### HeaderGroup Properties
- `getHeaderGroupProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Header Properties
- `getHeaderProps`
+6
View File
@@ -19,6 +19,12 @@
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows cells
### HeaderGroup Properties
- `getHeaderGroupProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Header Properties
- `getHeaderProps`
+1 -3
View File
@@ -9,12 +9,10 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.columnOrder: Array<ColumnId>`
- `initialState.columnOrder: Array<ColumnId>`
- Optional
- Defaults to `[]`
- Any column ID's not represented in this array will be naturally ordered based on their position in the original table's `column` structure
- `initialState.columnOrder`
- Identical to the `state.columnOrder` option above
### Instance Properties
+10 -15
View File
@@ -9,15 +9,13 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.expanded: Array<pathKey: String>`
- `initialState.expanded: Object<rowId: String, expanded: Bool>`
- Optional
- Must be **memoized**
- An array of expanded path keys.
- If a row's path key (`row.path.join('.')`) is present in this array, that row will have an expanded state. For example, if `['3']` was passed as the `expanded` state, the **4th row in the original data array** would be expanded.
- For nested expansion, you may **join the row path with a `.`** to expand sub rows. For example, if `['3', '3.5']` was passed as the `expanded` state, then the **6th subRow of the 4th row and also the 4th row of the original data array** would be expanded.
- An `object` of expanded row IDs with boolean property values.
- If a row's id is set to true in this object, that row will have an expanded state. For example, if `{ '3': true }` was passed as the `expanded` state, by default the **4th row in the original data array** would be expanded, since it would have that ID
- For nested expansion, you can **use nested IDs like `1.3`** to expand sub rows. For example, if `{ '3': true, '3.5': true }` was passed as the `expanded` state, then the **the 4th row would be expanded, along with the 6th subRow of the 4th row as well**.
- This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `initialState.expanded`
- Identical to the `state.expanded` option above
- `getSubRows: Function(row, relativeIndex) => Rows[]`
- Optional
- See the [useTable hook](#table-options) for more details
@@ -30,22 +28,19 @@ The following options are supported via the main options object passed to `useTa
- Defaults to `true`
- If set to `true`, expanded rows are rendered along with normal rows.
- If set to `false`, expanded rows will only be available through their parent row. This could be useful if you are implementing a custom expanded row view.
- `getResetExpandedDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `expanded` state to `[]` when the dependencies below change
- ```js
const getResetExpandedDeps = ({ data }) => [data]
```
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `expanded` state is fired.
- `autoResetExpanded: Boolean`
- Defaults to `true`
- When `true`, the `expanded` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](../faq.md#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
### Instance Properties
The following properties are available on the table instance returned from `useTable`
- `rows: Array<Row>`
- An array of **sorted** rows.
- An array of **expanded** rows.
### Row Properties
+94
View File
@@ -0,0 +1,94 @@
# `useFilters`
- Plugin Hook
- Optional
`useFilters` is the hook that implements **row filtering**.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `initialState.filters: Array<Object<id: String, value: any>>`
- Must be **memoized**
- An array of objects containing columnId's and their corresponding filter values. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `manualFilters: Bool`
- Enables filter detection functionality, but does not automatically perform row filtering.
- Turn this on if you wish to implement your own row filter outside of the table (eg. server-side or manual row grouping/nesting)
- `disableFilters: Bool`
- Disables filtering for every column in the entire table.
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, all columns will be filterable, regardless if they have a valid `accessor`
- `filterTypes: Object<filterKey: filterType>`
- Must be **memoized**
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the built-in filter types.
- For more information on filter types, see Filtering
- `autoResetFilters: Boolean`
- Defaults to `true`
- When `true`, the `filters` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
- `Filter: Function | React.Component => JSX`
- **Required**
- Receives the table instance and column model as props
- Must return valid JSX
- This function (or component) is used to render this column's filter UI, eg.
- `disableFilters: Bool`
- Optional
- If set to `true`, will disable filtering for this column
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, this column will be filterable, regardless if it has a valid `accessor`
- `filter: String | Function`
- Optional
- Defaults to `text`
- The resolved function from the this string/function will be used to filter the this column's data.
- If a `string` is passed, the function with that name located on either the custom `filterTypes` option or the built-in filtering types object will be used. If
- If a `function` is passed, it will be used directly.
- For more information on filter types, see Filtering
- If a **function** is passed, it must be **memoized**
### Instance Properties
The following values are provided to the table `instance`:
- `rows: Array<Row>`
- An array of **filtered** rows.
- `preFilteredRows: Array<Row>`
- The array of rows **used right before filtering**.
- Among many other use-cases, these rows are directly useful for building option lists in filters, since the resulting filtered `rows` do not contain every possible option.
- `setFilter: Function(columnId, filterValue) => void`
- An instance-level function used to update the filter value for a specific column.
- `setAllFilters: Function(filtersObject) => void`
- An instance-level function used to update the values for **all** filters on the table, all at once.
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `canFilter: Bool`
- Denotes whether a column is filterable or not depending on if it has a valid accessor/data model or is manually disabled via an option.
- `setFilter: Function(filterValue) => void`
- A column-level function used to update the filter value for this column
- `filterValue: any`
- The current filter value for this column, resolved from the table state's `filters` object
- `preFilteredRows: Array<row>`
- The array of rows that were originally passed to this columns filter **before** they were filtered.
- This array of rows can be useful if building faceted filter options.
- `filteredRows: Array<row>`
- The resulting array of rows received from this columns filter **after** they were filtered.
- This array of rows can be useful if building faceted filter options.
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
+43
View File
@@ -0,0 +1,43 @@
# `useFlexLayout`
- Plugin Hook
- Optional
`useFlexLayout` is a plugin hook that adds support for headers and cells to be rendered as `inline-block` `div`s (or other non-table elements) with `width` being used as the flex-basis and flex-grow. This hook becomes useful when implementing both virtualized and resizable tables that must also be able to stretch to fill all available space.
**NOTE:** Although no additional options are needed for this plugin to work, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set:
- `minWidth` is only used to limit column resizing. It does not define the minimum width for a column.
- `width` is used as both the `flex-basis` and `flex-grow`. This means that it essentially acts as both the minimum width and flex-ratio of the column.
- `maxWidth` is only used to limit column resizing. It does not define the maximum width for a column.
[See Column Options](#column-options) for more information on these options.
### Row Properties
- `getRowProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows
### Cell Properties
- `getCellProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows cells
### HeaderGroup Properties
- `getHeaderGroupProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Header Properties
- `getHeaderProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Example (Full Width Resizable Table)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/full-width-resizable-table)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/full-width-resizable-table)
+6 -6
View File
@@ -12,11 +12,9 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.groupBy: Array<String>`
- `initialState.groupBy: Array<String>`
- Must be **memoized**
- An array of groupBy ID strings, controlling which columns are used to calculate row grouping and aggregation. This information is stored in state since the table is allowed to manipulate the groupBy through user interaction.
- `initialState.groupBy`
- Identical to the `state.groupBy` option above
- `manualGroupBy: Bool`
- Enables groupBy detection and functionality, but does not automatically perform row grouping.
- Turn this on if you wish to implement your own row grouping outside of the table (eg. server-side or manual row grouping/nesting)
@@ -96,9 +94,11 @@ The following properties are available on every `Row` object returned by the tab
- If the row is a materialized group row, this property is the array of materialized subRows that were grouped inside of this row.
- `depth: Int`
- If the row is a materialized group row, this is the grouping depth at which this row was created.
- `path: Array<String|Int>`
- Similar to normal `Row` objects, materialized grouping rows also have a path array. The keys inside it though are not integers like nested normal rows though. Since they are not rows that can be traced back to an original data row, they are given a unique path based on their `groupByVal`
- If a row is a grouping row, it will have a path like `['Single']` or `['Complicated', 'Anderson']`, where `Single`, `Complicated`, and `Anderson` would all be derived from their row's `groupByVal`.
- `id: String`
- The unique ID for this row.
- This ID is unique across all rows, including sub rows
- Derived from the `getRowId` function, which defaults to chaining parent IDs and joining with a `.`
- If a row is a materialized grouping row, it will have an ID in the format of `columnId:groupByVal`.
- `isAggregated: Bool`
- Will be `true` if the row is an aggregated row
+13 -22
View File
@@ -11,36 +11,27 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.pageSize: Int`
- `initialState.pageSize: Int`
- **Required**
- Defaults to `10`
- Determines the amount of rows on any given page
- `initialState.pageSize`
- Identical to the `state.pageSize` option above
- `state.pageIndex: Int`
- `initialState.pageIndex: Int`
- **Required**
- Defaults to `0`
- The index of the page that should be displayed via the `page` instance value
- `initialState.pageIndex`
- Identical to the `state.pageIndex` option above
- `pageCount: Int`
- **Required if `manualPagination` is set to `true`**
- If `manualPagination` is `true`, then this value used to determine the amount of pages available. This amount is then used to materialize the `pageOptions` and also compute the `canNextPage` values on the table instance.
- `manualPagination: Bool`
- Enables pagination functionality, but does not automatically perform row pagination.
- Turn this on if you wish to implement your own pagination outside of the table (eg. server-side pagination or any other manual pagination technique)
- `getResetPageDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `pageIndex` to `0` when the dependencies below change
- ```js
const getResetPageDeps = ({
rows,
manualPagination,
state: { filters, groupBy, sortBy },
}) => [manualPagination ? null : rows, filters, groupBy, sortBy]
```
- Note that if `manualPagination` is set to `true`, then the pageIndex should not be reset when `rows` change
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `pageIndex` state is fired.
- `autoResetPage: Boolean`
- Defaults to `true`
- When `true`, the `pageIndex` state will automatically reset if `manualPagination` is `false` and any of the following conditions are met:
- `data` is changed
- `manualSortBy` is `false` and `state.sortBy` is changed
- `manualFilters` is `false` and `state.filters` is changed
- `manualGroupBy` is `false` and `state.groupBy` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
- `paginateExpandedRows: Bool`
@@ -54,6 +45,10 @@ The following options are supported via the main options object passed to `useTa
The following values are provided to the table `instance`:
- `state.pageIndex: Int`
- This is the current `pageIndex` value, located on the state.
- `state.pageSize: Int`
- This is the current `pageSize` value, located on the state.
- `page: Array<row>`
- An array of rows for the **current** page, determined by the current `pageIndex` value.
- `pageCount: Int`
@@ -78,10 +73,6 @@ The following values are provided to the table `instance`:
- `setPageSize: Function(pageSize)`
- This function sets `state.pageSize` to the new value.
- As a result of a pageSize change, a new `state.pageIndex` is also calculated. It is calculated via `Math.floor(currentTopRowIndex / newPageSize)`
- `pageIndex: Int`
- This is the resolved `state.pageIndex` value.
- `pageSize: Int`
- This is the resolved `state.pageSize` value.
### Example
+10 -13
View File
@@ -9,23 +9,18 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.selectedRowPaths: Set<RowPathKey>`
- `initialState.selectedRowIds: Object<rowId: Boolean>`
- Optional
- Defaults to `new Set()`
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have a selected state.
- `initialState.selectedRowPaths`
- Identical to the `state.selectedRowPaths` option above
- Defaults to `{}`
- If a row's ID is set to `true` in this object, it will have a selected state.
- `manualRowSelectedKey: String`
- Optional
- Defaults to `isSelected`
- If this key is found on the **original** data row, and it is true, this row will be manually selected
- `getResetSelectedRowPathsDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `expanded` state to `[]` when the dependencies below change
- ```js
const getResetSelectedRowPathsDeps = ({ rows }) => [rows]
```
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `selectedRowPaths` state is fired.
- `autoResetSelectedRows: Boolean`
- Defaults to `true`
- When `true`, the `selectedRowIds` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
@@ -36,7 +31,7 @@ The following values are provided to the table `instance`:
- `toggleRowSelected: Function(rowPath: String, ?set: Bool) => void`
- Use this function to toggle a row's selected state.
- Optionally pass `true` or `false` to set it to that state
- `toggleRowSelectedAll: Function(?set: Bool) => void`
- `toggleAllRowsSelected: Function(?set: Bool) => void`
- Use this function to toggle all rows as select or not
- Optionally pass `true` or `false` to set all rows to that state
- `getToggleAllRowsSelectedProps: Function(props) => props`
@@ -58,6 +53,8 @@ The following additional properties are available on every **prepared** `row` ob
- `isSelected: Bool`
- Will be `true` if the row is currently selected
- `isSomeSelected: Bool`
- Will be `true` if the row has subRows and at least one of them is currently selected
- `toggleRowSelected: Function(?set)`
- Use this function to toggle this row's selected state.
- Optionally pass `true` or `false` to set it to that state
+8 -13
View File
@@ -9,25 +9,20 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.rowState: Object<RowPathKey:Object<any, cellState: {columnId: Object}>>`
- `initialState.rowState: Object<RowPathKey:Object<any, cellState: {columnId: Object}>>`
- Optional
- Defaults to `{}`
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have the state of the value corresponding to that key.
- If a row's ID is found in this array, it will have the state of the value corresponding to that key.
- Individual row states can contain anything, but they also contain a `cellState` key, which provides cell-level state based on column ID's to every
**prepared** cell in the table.
- `initialState.rowState`
- Identical to the `state.rowState` option above
- `initialRowStateAccessor: Function`
- Optional
- This function may optionally return the initial state for a row.
- If this function is defined, it will be passed a `Row` object, from which you can return a value to use as the initial state, eg. `row => row.original.initialState`
- `getResetRowStateDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `rowState` state to `{}` when the dependencies below change
- ```js
const getResetRowStateDeps = ({ data }) => [data]
```
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `rowState` state is fired.
- `autoResetRowState: Boolean`
- Defaults to `true`
- When `true`, the `rowState` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
@@ -47,7 +42,7 @@ The following values are provided to the table `instance`:
The following additional properties are available on every **prepared** `row` object returned by the table instance.
- `state: Object`
- This is the state object for each row, pre-mapped to the row from the table state's `rowState` object via `rowState[row.path.join('.')]`
- This is the state object for each row, pre-mapped to the row from the table state's `rowState` object via `rowState[row.id]`
- May also contain a `cellState` key/value pair, which is used to provide individual cell states to this row's cells
- `setState: Function(updater: Function | any)`
- Use this function to programmatically update the state of a row.
@@ -58,7 +53,7 @@ The following additional properties are available on every **prepared** `row` ob
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
- `state: Object`
- This is the state object for each cell, pre-mapped to the cell from the table state's `rowState` object via `rowState[row.path.join('.')].cellState[columnId]`
- This is the state object for each cell, pre-mapped to the cell from the table state's `rowState` object via `rowState[row.id].cellState[columnId]`
- `setState: Function(updater: Function | any)`
- Use this function to programmatically update the state of a cell.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
+6 -105
View File
@@ -14,12 +14,10 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.sortBy: Array<Object<id: columnId, desc: Bool>>`
- `initialState.sortBy: Array<Object<id: columnId, desc: Bool>>`
- Must be **memoized**
- An array of sorting objects. If there is more than one object in the array, multi-sorting will be enabled. Each sorting object should contain an `id` key with the corresponding column ID to sort by. An optional `desc` key may be set to true or false to indicated ascending or descending sorting for that column. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `initialState.sortBy`
- Identical to the `state.sortBy` option above
- `manualSorting: Bool`
- `manualSortBy: Bool`
- Enables sorting detection functionality, but does not automatically perform row sorting. Turn this on if you wish to implement your own sorting outside of the table (eg. server-side or manual row grouping/nesting)
- `disableSortBy: Bool`
- Disables sorting for every column in the entire table.
@@ -46,10 +44,10 @@ The following options are supported via the main options object passed to `useTa
- Must be **memoized**
- Allows overriding or adding additional sort types for columns to use. If a column's sort type isn't found on this object, it will default to using the built-in sort types.
- For more information on sort types, see Sorting
- `getResetSortByDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to `false`
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `sortBy` state is fired.
- `autoResetSortBy: Boolean`
- Defaults to `true`
- When `true`, the `sortBy` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
@@ -125,100 +123,3 @@ The following properties are available on every `Column` object returned by the
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/sorting)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting)
# `useFilters`
- Plugin Hook
- Optional
`useFilters` is the hook that implements **row filtering**.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.filters: Object<columnId: filterValue>`
- Must be **memoized**
- An object of columnId's and their corresponding filter values. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `initialState.filters`
- Identical to the `state.filters` option above
- `manualFilters: Bool`
- Enables filter detection functionality, but does not automatically perform row filtering.
- Turn this on if you wish to implement your own row filter outside of the table (eg. server-side or manual row grouping/nesting)
- `disableFilters: Bool`
- Disables filtering for every column in the entire table.
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, all columns will be filterable, regardless if they have a valid `accessor`
- `filterTypes: Object<filterKey: filterType>`
- Must be **memoized**
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the built-in filter types.
- For more information on filter types, see Filtering
- `getResetFiltersDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to `false`
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `filters` state is fired.
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
- `Filter: Function | React.Component => JSX`
- **Required**
- Receives the table instance and column model as props
- Must return valid JSX
- This function (or component) is used to render this column's filter UI, eg.
- `disableFilters: Bool`
- Optional
- If set to `true`, will disable filtering for this column
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, this column will be filterable, regardless if it has a valid `accessor`
- `filter: String | Function`
- Optional
- Defaults to `text`
- The resolved function from the this string/function will be used to filter the this column's data.
- If a `string` is passed, the function with that name located on either the custom `filterTypes` option or the built-in filtering types object will be used. If
- If a `function` is passed, it will be used directly.
- For more information on filter types, see Filtering
- If a **function** is passed, it must be **memoized**
### Instance Properties
The following values are provided to the table `instance`:
- `rows: Array<Row>`
- An array of **filtered** rows.
- `preFilteredRows: Array<Row>`
- The array of rows **used right before filtering**.
- Among many other use-cases, these rows are directly useful for building option lists in filters, since the resulting filtered `rows` do not contain every possible option.
- `setFilter: Function(columnId, filterValue) => void`
- An instance-level function used to update the filter value for a specific column.
- `setAllFilters: Function(filtersObject) => void`
- An instance-level function used to update the values for **all** filters on the table, all at once.
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `canFilter: Bool`
- Denotes whether a column is filterable or not depending on if it has a valid accessor/data model or is manually disabled via an option.
- `setFilter: Function(filterValue) => void`
- A column-level function used to update the filter value for this column
- `filterValue: any`
- The current filter value for this column, resolved from the table state's `filters` object
- `preFilteredRows: Array<row>`
- The array of rows that were originally passed to this columns filter **before** they were filtered.
- This array of rows can be useful if building faceted filter options.
- `filteredRows: Array<row>`
- The resulting array of rows received from this columns filter **after** they were filtered.
- This array of rows can be useful if building faceted filter options.
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
+14 -9
View File
@@ -53,13 +53,11 @@ The following options are supported via the main options object passed to `useTa
- Defaults to `(row) => row.subRows || []`
- Use this function to change how React Table detects subrows. You could even use this function to generate sub rows if you want.
- By default, it will attempt to return the `subRows` property on the row, or an empty array if that is not found.
- `getRowId: Function(row, relativeIndex) => string`
- Use this function to change how React Table detects unique rows and also how it constructs each row's underlying `path` property.
- `getRowId: Function(row, relativeIndex, ?parent) => string`
- Use this function to change how React Table detects unique rows and also how it constructs each row's underlying `id` property.
- Optional
- Must be **memoized**
- Defaults to `(row, relativeIndex) => relativeIndex`
- You may want to change this function if
- By default, it will use the `index` of the row within it's original array.
- Defaults to `(row, relativeIndex, parent) => parent ? [parent.id, relativeIndex].join('.') : relativeIndex`
- `debug: Bool`
- Optional
- A flag to turn on debug mode.
@@ -95,6 +93,11 @@ The following options are supported on any column object you can pass to `column
- Receives the table instance and cell model as props
- Must return valid JSX
- This function (or component) is primarily used for formatting the column value, eg. If your column accessor returns a date object, you can use a `Cell` function to format that date to a readable format.
- `show: Bool`
- Optional
- Defaults to `undefined`
- If set to `true`, will take priority over any state in `hiddenColumns` and force this column to be visible at all times.
- If set to `false` will take priority over any state in `hiddenColumns` and force this column to be hidden at all times.
- `width: Int`
- Optional
- Defaults to `150`
@@ -242,7 +245,12 @@ The following properties are available on every `Column` object returned by the
The following additional properties are available on every `row` object returned by the table instance.
- `cells: Array<Cell>`
- An array of `Cell` objects containing properties and functions specific to the row and column it belongs to.
- An array of visible `Cell` objects containing properties and functions specific to the row and column it belongs to.
- These cells are normally intended for display
- See [Cell Properties](#cell-properties) for more information
- `allCells: Array<Cell>`
- An array of all `Cell` objects containing properties and functions specific to the row and column it belongs to.
- Not every cell contained here is guaranteed that it should be displayed and is made available here for convenience and advanced templating purposes.
- See [Cell Properties](#cell-properties) for more information
- `values: Object<columnId: any>`
- A map of this row's **resolved** values by columnId, eg. `{ firstName: 'Tanner', lastName: 'Linsley' }`
@@ -255,9 +263,6 @@ The following additional properties are available on every `row` object returned
- The index of the original row in the `data` array that was passed to `useTable`. If this row is a subRow, it is the original index within the parent row's subRows array
- `original: Object`
- The original row object from the `data` array that was used to materialize this row.
- `path: Array<string>`
- This array is the sequential path of indices one could use to navigate to it, eg. a row path of `[3, 1, 0]` would mean that it is the **first** subRow of a parent that is the **second** subRow of a parent that is the **fourth** row in the original `data` array.
- This array is used with plugin hooks like `useExpanded` and `useGroupBy` to compute expanded states for individual rows.
- `subRows: Array<Row>`
- If subRows were detect on the original data object, this will be an array of those materialized row objects.
- `state: Object`
+9
View File
@@ -16,6 +16,9 @@
- Grouping
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/grouping)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping)
- Grouping (Single Column)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/grouping-column)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping-column)
- Pagination
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination)
@@ -46,6 +49,12 @@
- Row DnD
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/row-dnd)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-dnd)
- Full Width Table (Table Elements with collapsible content)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/full-width-table)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/full-width-table)
- Full Width Resizable Table (via `useFlexLayout`)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/full-width-resizable-table)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/full-width-resizable-table)
- **Complex**
- The "Kitchen Sink"
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
+68 -8
View File
@@ -26,36 +26,96 @@ useTable({
})
```
**It's important that the state override is done within a `useMemo` call to prevent the state variable from changing on every render. It's also just as important that you always use the `state` in any memoization dependencies to ensure that you do not block normal state updates.**
> **It's important that the state override is done within a `useMemo` call to prevent the state variable from changing on every render. It's also extremely important that you always use the `state` in any dependencies to ensure that you do not block normal state updates.**
## How can I use the table state to fetch new data?
When managing your data externally or asynchronously (eg. server-side pagination/sorting/grouping/etc), you will need to fetch new data as the internal table state changes. With React Hooks, this is fantastically easier than it was before now that we have the `React.useEffect` hook. We can use this hook to "watch" the table state for specific changes and use those effects to trigger fetches for new data (or synchronize any other state you may be managing externally from your table component):
```js
function Table({ data, onFetchData }) {
const {
state: { pageIndex, pageSize, sortBy, filters },
} = useTable({
data,
})
// When the these table states change, fetch new data!
React.useEffect(() => {
onFetchData({ pageIndex, pageSize, sortBy, filters })
}, [fetchData, pageIndex, pageSize, sortBy, filters])
return </>
}
```
Using this approach, you can respond and trigger any type of side-effect using the table instance!
## How can I debounce rapid table state changes?
React Table has a few built-in side-effects of it's own (most of which are meant for resetting parts of the state when `data` changes). By default, these state side-effects are on and when their conditions are met, they immediately fire off actions that will manipulate the table state. Sometimes, this may result in multiple rapid rerenders (usually just 2, or one more than normal), and could cause any side-effects you have watching the table state to also fire multiple times in-a-row. To alleviate this edge-case, React Table exports a `useAsyncDebounce` function that will allow you to debounce rapid side-effects and only use the latest one.
A good example of this when doing server-side pagination and sorting, a user changes the `sortBy` for a table and the `pageIndex` is automatically reset to `0` via an internal side effect. This would normally cause our effect below to fire 2 times, but with `useAsyncDebounce` we can make sure our data fetch function only gets called once:
```js
import { useTable, useAsyncDebounce } from 'react-table'
function Table({ data, onFetchData }) {
const {
state: { pageIndex, pageSize, sortBy, filters },
} = useTable({
data,
})
// Debounce our onFetchData call for 100ms
const onFetchDataDebounced = useAsyncDebounce(onFetchData, 100)
// When the these table states changes, fetch new data!
React.useEffect(() => {
// Every change will call our debounced function
onFetchDataDebounced({ pageIndex, pageSize, sortBy, filters })
// Only the last call after the 100ms debounce is over will be fired!
}, [onFetchDataDebounced, pageIndex, pageSize, sortBy, filters])
return </>
}
```
## How do I stop my table state from automatically resetting when my data changes?
Most plugins use state that _should_ normally reset when the data sources changes, but sometimes you need to suppress that from happening if you are filtering your data externally, or immutably editing your data while looking at it, or simply doing anything external with your data that you don't want to trigger a piece of table state to reset automatically.
For those situations, each plugin provides options like `getResetPageDeps` or `getResetExpandedDeps`, so and an so forth. These functions are provided the table `instance` and allowed to return an array of variables that will be injected into the `React.useEffect`'s dependency array that is responsible for watching and resetting those states. By returning a new array in one of these arrays, you can either stop the automatic resets from being triggered, or even trigger them more based on what you are returning. You can also return `false` for any of these options to disable the automatic resets completely, or pass `undefined` to allow the default dependendies to be used.
For those situations, each plugin provides a way to disable the state from automatically resetting internally when data or other dependencies for a piece of state change. By setting any of them to `false`, you can stop the automatic resets from being triggered.
Here is an example of completely disabling the page from resetting when data changes:
Here is an example of stopping basically every piece of state from changing as they normally do while we edit the `data` source for a table:
```js
const [data, setData] = React.useState([])
const skipPageResetRef = React.useRef()
const updateData = newData => {
// When data gets updated with this function, disable the
// page from resetting
// When data gets updated with this function, set a flag
// to disable all of the auto resetting
skipPageResetRef.current = true
setData(newData)
}
React.useEffect(() => {
// After the table has updated, always remove the flag
skipPageResetRef.current = false
})
useTable({
data,
getResetPageDeps: skipPageReset ? false : undefined,
...
autoResetPage: !skipPageReset,
autoResetExpanded: !skipPageReset,
autoResetGroupBy: !skipPageReset,
autoResetSelectedRows: !skipPageReset,
autoResetSortBy: !skipPageReset,
autoResetFilters: !skipPageReset,
autoResetRowState: !skipPageReset,
})
```
<!-- ## How can I hide/show columns? -->
Now, when we update our data, the above table states will not automatically reset!
+12 -13
View File
@@ -92,19 +92,18 @@ function Table({ columns, data }) {
</div>
<div className="rows" {...getTableBodyProps()}>
{rows.map(
(row, i) => {
prepareRow(row);
return (
<div {...row.getRowProps()} className="row body">
{row.cells.map((cell,index) => (
<div {...cell.getCellProps()} key={index} className="cell">
{cell.render('Cell')}
</div>
))}
</div>
)}
)}
{rows.map((row, i) => {
prepareRow(row)
return (
<div {...row.getRowProps()} className="row body">
{row.cells.map((cell, index) => (
<div {...cell.getCellProps()} key={index} className="cell">
{cell.render('Cell')}
</div>
))}
</div>
)
})}
</div>
</div>
)
+3 -3
View File
@@ -35,18 +35,18 @@ const Styles = styled.div`
border-right: 0;
}
${'' /* The resizer styles! */}
.resizer {
display: inline-block;
background: blue;
width: 5px;
width: 10px;
height: 100%;
position: absolute;
right: 0;
top: 0;
transform: translateX(50%);
z-index: 1;
${'' /* prevents from scrolling while dragging on touch devices */}
touch-action:none;
&.isResizing {
background: red;
+4 -4
View File
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.7.tgz#1bf3e248cdef22213821c021236e895bdc3cb5d2"
integrity sha512-24Yofwkh822NyCmnpsrChV8SNOCENQWpV4A5f/MzapTi6iwje644Q11/wbLIgJdPnUJJ0/JbhjsDjxlB6yFV7Q==
react@^16.8.6:
version "16.8.6"
@@ -1,6 +1,6 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, mergeProps } from 'react-table'
import { useTable } from 'react-table'
import makeData from './makeData'
@@ -68,16 +68,15 @@ function Table({
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th
// Merge all of the header Props
{...mergeProps(
column.getHeaderProps(),
// Return an array of prop objects and react-table will merge them appropriately
{...column.getHeaderProps([
{
className: column.className,
style: column.style,
},
getColumnProps(column),
getHeaderProps(column)
)}
getHeaderProps(column),
])}
>
{column.render('Header')}
</th>
@@ -89,21 +88,20 @@ function Table({
{rows.map((row, i) => {
prepareRow(row)
return (
// Merge row props
<tr {...mergeProps(row.getRowProps(), getRowProps(row))}>
// Merge user row props in
<tr {...row.getRowProps(getRowProps(row))}>
{row.cells.map(cell => {
return (
<td
// Merge cell props
{...mergeProps(
cell.getCellProps(),
// Return an array of prop objects and react-table will merge them appropriately
{...cell.getCellProps([
{
className: cell.column.className,
style: cell.column.style,
},
getColumnProps(cell.column),
getCellProps(cell)
)}
getCellProps(cell),
])}
>
{cell.render('Cell')}
</td>
+1 -1
View File
@@ -102,7 +102,7 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
data,
defaultColumn,
// use the skipPageReset option to disable page resetting temporarily
getResetPageDeps: skipPageReset ? false : undefined,
autoResetPage: !skipPageReset,
// updateMyData isn't part of the API, but
// anything we put into these options will
// automatically be available on the instance.
+11 -14
View File
@@ -62,25 +62,22 @@ function Table({ columns: userColumns, data }) {
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)}
)}
{rows.map((row, i) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
<br />
<div>Showing the first 20 results of {rows.length} rows</div>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
<code>{JSON.stringify({ expanded: expanded }, null, 2)}</code>
</pre>
</>
)
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+4
View File
@@ -0,0 +1,4 @@
# Full Width Resizable Table (via useFlexLayout)
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/full-width-resizable-table)
- `yarn` and `yarn start` to run and edit the example
+35
View File
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "latest",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+38
View File
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+3
View File
@@ -0,0 +1,3 @@
{
"infiniteLoopProtection": false
}
+193
View File
@@ -0,0 +1,193 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useResizeColumns, useFlexLayout } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
.table {
${'' /* These styles are suggested for the table fill all available space in its containing element */}
display: block;
${'' /* These styles are required for a horizontaly scrollable table overflow */}
overflow: auto;
border-spacing: 0;
border: 1px solid black;
.thead {
${'' /* These styles are required for a scrollable body to align with the header properly */}
overflow-y: auto;
overflow-x: hidden;
}
.tbody {
${'' /* These styles are required for a scrollable table body */}
overflow-y: scroll;
overflow-x: hidden;
height: 250px;
}
.tr {
:last-child {
.td {
border-bottom: 0;
}
}
}
.th,
.td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
${'' /* In this example we use an absolutely position resizer,
so this is required. */}
position: relative;
:last-child {
border-right: 0;
}
.resizer {
display: inline-block;
background: blue;
width: 10px;
height: 100%;
position: absolute;
right: 0;
top: 0;
z-index: 1;
${'' /* prevents from scrolling while dragging on touch devices */}
touch-action:none;
&.isResizing {
background: red;
}
}
}
}
`
function Table({ columns, data }) {
const defaultColumn = React.useMemo(
() => ({
// When using the useFlexLayout:
minWidth: 30, // minWidth is only used as a limit for resizing
width: 150, // width is used for both the flex-basis and flex-grow
maxWidth: 200, // maxWidth is only used as a limit for resizing
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
defaultColumn,
},
useResizeColumns,
useFlexLayout
)
return (
<div {...getTableProps()} className="table">
<div>
{headerGroups.map(headerGroup => (
<div {...headerGroup.getHeaderGroupProps()} className="tr">
{headerGroup.headers.map(column => (
<div {...column.getHeaderProps()} className="th">
{column.render('Header')}
{/* Use column.getResizerProps to hook up the events correctly */}
<div
{...column.getResizerProps()}
className={`resizer ${column.isResizing ? 'isResizing' : ''}`}
/>
</div>
))}
</div>
))}
</div>
<div {...getTableBodyProps()} className="tbody">
{rows.map((row, i) => {
prepareRow(row)
return (
<div {...row.getRowProps()} className="tr">
{row.cells.map(cell => {
return (
<div {...cell.getCellProps()} className="td">
{cell.render('Cell')}
</div>
)
})}
</div>
)
})}
</div>
</div>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
width: 50,
},
{
Header: 'Visits',
accessor: 'visits',
width: 50,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(20), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
+9
View File
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+6
View File
@@ -0,0 +1,6 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
ReactDOM.render(<App />, document.getElementById('root'))
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+6
View File
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping-column)
- `yarn` and `yarn start` to run and edit the example
+35
View File
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "latest",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
@@ -0,0 +1,3 @@
{
"infiniteLoopProtection": false
}
+305
View File
@@ -0,0 +1,305 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useGroupBy, useExpanded } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
`
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
state: { groupBy, expanded },
} = useTable(
{
columns,
data,
},
useGroupBy,
useExpanded,
// Our custom plugin to add the expander column
hooks => {
hooks.flatColumns.push((columns, instance) => {
if (!instance.state.groupBy.length) {
return columns
}
return [
{
id: 'expander', // Make sure it has an ID
// Build our expander column
Header: ({ flatColumns, state: { groupBy } }) => {
return groupBy.map(columnId => {
const column = flatColumns.find(d => d.id === columnId)
return (
<span {...column.getHeaderProps()}>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.isGrouped ? '🛑 ' : '👊 '}
</span>
) : null}
{column.render('Header')}{' '}
</span>
)
})
},
Cell: ({ row }) => {
if (row.canExpand) {
const groupedCell = row.allCells.find(d => d.isGrouped)
return (
<span
{...row.getExpandedToggleProps({
style: {
// We can even use the row.depth property
// and paddingLeft to indicate the depth
// of the row
paddingLeft: `${row.depth * 2}rem`,
},
})}
>
{row.isExpanded ? '👇' : '👉'} {groupedCell.render('Cell')}{' '}
({row.subRows.length})
</span>
)
}
return null
},
},
...columns.map(d => ({ ...d, isVisible: !d.isGrouped })),
]
})
}
)
// We don't want to render all of the rows for this example, so cap
// it at 20 for this use case
const firstPageRows = rows.slice(0, 100)
return (
<>
<pre>
<code>{JSON.stringify({ groupBy, expanded: expanded }, null, 2)}</code>
</pre>
<Legend />
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.isGrouped ? '🛑 ' : '👊 '}
</span>
) : null}
{column.render('Header')}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{firstPageRows.map((row, i) => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td
// For educational purposes, let's color the
// cell depending on what type it is given
// from the useGroupBy hook
{...cell.getCellProps()}
style={{
background: cell.isGrouped
? '#0aff0082'
: cell.isAggregated
? '#ffa50078'
: cell.isRepeatedValue
? '#ff000042'
: 'white',
}}
>
{cell.isAggregated
? // If the cell is aggregated, use the Aggregated
// renderer for cell
cell.render('Aggregated')
: cell.isRepeatedValue
? null // For cells with repeated values, render null
: // Otherwise, just render the regular cell
cell.render('Cell')}
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
<br />
<div>Showing the first 100 results of {rows.length} rows</div>
</>
)
}
function Legend() {
return (
<div
style={{
padding: '0.5rem 0',
}}
>
<span
style={{
display: 'inline-block',
background: '#0aff0082',
padding: '0.5rem',
}}
>
Grouped
</span>{' '}
<span
style={{
display: 'inline-block',
background: '#ffa50078',
padding: '0.5rem',
}}
>
Aggregated
</span>{' '}
<span
style={{
display: 'inline-block',
background: '#ff000042',
padding: '0.5rem',
}}
>
Repeated Value
</span>
</div>
)
}
// This is a custom aggregator that
// takes in an array of values and
// returns the rounded median
function roundedMedian(values) {
let min = values[0] || ''
let max = values[0] || ''
values.forEach(value => {
min = Math.min(min, value)
max = Math.max(max, value)
})
return Math.round((min + max) / 2)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
// Use a two-stage aggregator here to first
// count the total rows being aggregated,
// then sum any of those counts if they are
// aggregated further
aggregate: ['sum', 'count'],
Aggregated: ({ cell: { value } }) => `${value} Names`,
},
{
Header: 'Last Name',
accessor: 'lastName',
// Use another two-stage aggregator here to
// first count the UNIQUE values from the rows
// being aggregated, then sum those counts if
// they are aggregated further
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
// Aggregate the average age of visitors
aggregate: 'average',
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
// Aggregate the sum of all visits
aggregate: 'sum',
Aggregated: ({ cell: { value } }) => `${value} (total)`,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
// Use our custom roundedMedian aggregator
aggregate: roundedMedian,
Aggregated: ({ cell: { value } }) => `${value} (med)`,
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(100000), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
+9
View File
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+6
View File
@@ -0,0 +1,6 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
ReactDOM.render(<App />, document.getElementById('root'))
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
File diff suppressed because it is too large Load Diff
+12 -12
View File
@@ -3652,16 +3652,16 @@ eslint-scope@^4.0.0, eslint-scope@^4.0.3:
estraverse "^4.1.1"
eslint-utils@^1.3.1:
version "1.4.0"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.0.tgz#e2c3c8dba768425f897cf0f9e51fe2e241485d4c"
integrity sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==
version "1.4.3"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f"
integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==
dependencies:
eslint-visitor-keys "^1.0.0"
eslint-visitor-keys "^1.1.0"
eslint-visitor-keys@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#3f3180fb2e291017716acb4c9d6d5b5c34a6a81d"
integrity sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==
eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2"
integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A==
eslint@^5.16.0:
version "5.16.0"
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.1"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.1.tgz#33f61b904d246d862a46a05ac4d8eda6343ea83b"
integrity sha512-tAuZg+TY64UUgBPRts/q+0JguGZpliYdoQZl7lAnLAQ/reU/5c04sCx54QcpH7n/PYVHMJEYkIU0ito8ZZ011w==
react@^16.8.6:
version "16.8.6"
+30 -32
View File
@@ -282,14 +282,7 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
nextPage,
previousPage,
setPageSize,
state: {
pageIndex,
pageSize,
groupBy,
expanded,
filters,
selectedRowPaths,
},
state: { pageIndex, pageSize, groupBy, expanded, filters, selectedRowIds },
} = useTable(
{
columns,
@@ -306,14 +299,39 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
updateMyData,
// We also need to pass this so the page doesn't change
// when we edit the data, undefined means using the default
getResetPageDeps: skipPageReset ? false : undefined,
autoResetPage: !skipPageReset,
},
useGroupBy,
useFilters,
useSortBy,
useExpanded,
usePagination,
useRowSelect
useRowSelect,
hooks => {
hooks.flatColumns.push(columns => [
{
id: 'selection',
// Make this column a groupByBoundary. This ensures that groupBy columns
// are placed after it
groupByBoundary: true,
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
])
}
)
// Render the UI for your table
@@ -440,9 +458,9 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
canNextPage,
canPreviousPage,
groupBy,
expanded,
expanded: expanded,
filters,
selectedRowPaths: [...selectedRowPaths.values()],
selectedRowIds: selectedRowIds,
},
null,
2
@@ -485,26 +503,6 @@ function roundedMedian(values) {
function App() {
const columns = React.useMemo(
() => [
{
id: 'selection',
// Make this column a groupByBoundary. This ensures that groupBy columns
// are placed after it
groupByBoundary: true,
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
{
Header: 'Name',
columns: [
+52 -34
View File
@@ -282,14 +282,7 @@ function Table({ columns, data, updateMyData, skipReset }) {
nextPage,
previousPage,
setPageSize,
state: {
pageIndex,
pageSize,
groupBy,
expanded,
filters,
selectedRowPaths,
},
state: { pageIndex, pageSize, groupBy, expanded, filters, selectedRowIds },
} = useTable(
{
columns,
@@ -303,16 +296,44 @@ function Table({ columns, data, updateMyData, skipReset }) {
// cell renderer!
updateMyData,
// We also need to pass this so the page doesn't change
// when we edit the data. Undefined tells it to use the default
getResetPageDeps: skipReset ? false : undefined,
getResetSelectedRowPathsDeps: skipReset ? false : undefined,
// when we edit the data.
autoResetPage: !skipReset,
autoResetSelectedRows: !skipReset,
},
useFilters,
useGroupBy,
useSortBy,
useExpanded,
usePagination,
useRowSelect
useRowSelect,
// Here we will use a plugin to add our selection column
hooks => {
hooks.flatColumns.push(columns => {
return [
{
id: 'selection',
// Make this column a groupByBoundary. This ensures that groupBy columns
// are placed after it
groupByBoundary: true,
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
]
})
}
)
// Render the UI for your table
@@ -439,9 +460,9 @@ function Table({ columns, data, updateMyData, skipReset }) {
canNextPage,
canPreviousPage,
groupBy,
expanded,
expanded: expanded,
filters,
selectedRowPaths: [...selectedRowPaths.values()],
selectedRowIds: selectedRowIds,
},
null,
2
@@ -481,29 +502,26 @@ function roundedMedian(values) {
return Math.round((min + max) / 2)
}
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
function App() {
const columns = React.useMemo(
() => [
{
id: 'selection',
// Make this column a groupByBoundary. This ensures that groupBy columns
// are placed after it
groupByBoundary: true,
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
{
Header: 'Name',
columns: [
+4 -4
View File
@@ -8218,10 +8218,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-beta.19"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-beta.19.tgz#8563ae56f693cbffa10060772ba1f1cd4e926bb2"
integrity sha512-BRt7zW7PGyg67fR2CK9M2fwP6BocjQN870w3P+K+vDJMkpewGjSPDscCU5sJMBqCEjKWg85k2pVkiwQPg9ofgQ==
react-table@latest:
version "7.0.0-rc.6"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.6.tgz#3cb43919e31166659d6aa223bd3dfee765981f6b"
integrity sha512-iFgxMla6JnxjZwKG3eiHHOlIIANiK/HzvRFWXT8LV78N9bEOGC5A5N44S/xQ1PaZN/1c+NDBz5fBazhx/vG7/A==
react@^16.8.6:
version "16.12.0"
+12 -5
View File
@@ -77,8 +77,6 @@ function Table({
usePagination
)
// Now we can get our table state from the hoisted table state tuple
// Listen for changes in pagination and use the state to fetch our new data
React.useEffect(() => {
fetchData({ pageIndex, pageSize })
@@ -107,7 +105,16 @@ function Table({
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
<th {...column.getHeaderProps()}>
{column.render('Header')}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</th>
))}
</tr>
))}
@@ -126,9 +133,9 @@ function Table({
<tr>
{loading ? (
// Use our custom loading state to show a loading indicator
<td>Loading...</td>
<td colSpan="10000">Loading...</td>
) : (
<td>
<td colSpan="10000">
Showing {page.length} of ~{controlledPageCount * pageSize}{' '}
results
</td>
+4 -4
View File
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.1"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.1.tgz#33f61b904d246d862a46a05ac4d8eda6343ea83b"
integrity sha512-tAuZg+TY64UUgBPRts/q+0JguGZpliYdoQZl7lAnLAQ/reU/5c04sCx54QcpH7n/PYVHMJEYkIU0ito8ZZ011w==
react@^16.8.6:
version "16.8.6"
-1
View File
@@ -62,7 +62,6 @@ function Table({ columns, data }) {
columns,
data,
initialState: { pageIndex: 2 },
debug: true,
},
usePagination
)
+4 -4
View File
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.1"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.1.tgz#33f61b904d246d862a46a05ac4d8eda6343ea83b"
integrity sha512-tAuZg+TY64UUgBPRts/q+0JguGZpliYdoQZl7lAnLAQ/reU/5c04sCx54QcpH7n/PYVHMJEYkIU0ito8ZZ011w==
react@^16.8.6:
version "16.8.6"
+45 -24
View File
@@ -33,6 +33,23 @@ const Styles = styled.div`
}
`
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
@@ -42,14 +59,36 @@ function Table({ columns, data }) {
rows,
prepareRow,
selectedFlatRows,
state: { selectedRowPaths },
state: { selectedRowIds },
} = useTable(
{
columns,
data,
debug: true,
},
useRowSelect
useRowSelect,
hooks => {
hooks.flatColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
])
}
)
// Render the UI for your table
@@ -78,12 +117,12 @@ function Table({ columns, data }) {
})}
</tbody>
</table>
<p>Selected Rows: {selectedRowPaths.size}</p>
<p>Selected Rows: {Object.keys(selectedRowIds).length}</p>
<pre>
<code>
{JSON.stringify(
{
selectedRowPaths: [...selectedRowPaths.values()],
selectedRowIds: selectedRowIds,
'selectedFlatRows[].original': selectedFlatRows.map(
d => d.original
),
@@ -100,24 +139,6 @@ function Table({ columns, data }) {
function App() {
const columns = React.useMemo(
() => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
{
Header: 'Name',
columns: [
@@ -156,7 +177,7 @@ function App() {
[]
)
const data = React.useMemo(() => makeData(10), [])
const data = React.useMemo(() => makeData(10, 3), [])
return (
<Styles>
+12 -12
View File
@@ -3652,16 +3652,16 @@ eslint-scope@^4.0.0, eslint-scope@^4.0.3:
estraverse "^4.1.1"
eslint-utils@^1.3.1:
version "1.4.0"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.0.tgz#e2c3c8dba768425f897cf0f9e51fe2e241485d4c"
integrity sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==
version "1.4.3"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f"
integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==
dependencies:
eslint-visitor-keys "^1.0.0"
eslint-visitor-keys "^1.1.0"
eslint-visitor-keys@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#3f3180fb2e291017716acb4c9d6d5b5c34a6a81d"
integrity sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==
eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2"
integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A==
eslint@^5.16.0:
version "5.16.0"
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.6"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.6.tgz#3cb43919e31166659d6aa223bd3dfee765981f6b"
integrity sha512-iFgxMla6JnxjZwKG3eiHHOlIIANiK/HzvRFWXT8LV78N9bEOGC5A5N44S/xQ1PaZN/1c+NDBz5fBazhx/vG7/A==
react@^16.8.6:
version "16.8.6"
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+6
View File
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/streaming-rows)
- `yarn` and `yarn start` to run and edit the example
+36
View File
@@ -0,0 +1,36 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "latest",
"react-window": "^1.8.5",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+38
View File
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
@@ -0,0 +1,5 @@
{
"infiniteLoopProtection": false,
"hardReloadOnChange": false,
"view": "browser"
}
+217
View File
@@ -0,0 +1,217 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useBlockLayout, useRowSelect } from 'react-table'
const Styles = styled.div`
padding: 1rem;
.table {
display: inline-block;
border-spacing: 0;
border: 1px solid black;
.tr {
:last-child {
.td {
border-bottom: 0;
}
}
}
.th,
.td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
`
let sourceGridData = []
const updateRateMS = 16
function Table({ columns }) {
// Use the state and functions returned from useTable to build your UI
const [data, setData] = React.useState([])
const timerRunning = React.useRef()
if (!timerRunning.current) {
timerRunning.current = true
setInterval(() => {
sourceGridData.push(makeRow(sourceGridData.length))
let newData = [...sourceGridData]
setData(newData)
}, updateRateMS)
}
const defaultColumn = React.useMemo(
() => ({
width: 150,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
toggleAllRowsSelected,
prepareRow,
state,
} = useTable(
{
autoResetSelectedRows: false,
columns,
data,
defaultColumn,
},
useBlockLayout,
useRowSelect
)
// Render the UI for your table
return (
<>
<div {...getTableProps()} className="table">
<div className="thead">
{headerGroups.map(headerGroup => (
<div {...headerGroup.getHeaderGroupProps()} className="tr">
{headerGroup.headers.map(column => (
<div {...column.getHeaderProps()} className="th">
{column.render('Header')}
</div>
))}
</div>
))}
</div>
<div {...getTableBodyProps()}>
{rows.slice(0, 10).map(row => {
prepareRow(row)
return (
<div
{...row.getRowProps({
style: {
backgroundColor: row.isSelected ? 'green' : '',
},
onClick: e => {
toggleAllRowsSelected(false)
row.toggleRowSelected()
},
})}
className="tr"
>
{row.cells.map(cell => {
return (
<div {...cell.getCellProps()} className="td">
{cell.render('Cell')}
</div>
)
})}
</div>
)
})}
</div>
</div>
<pre>
<code>{JSON.stringify(state, null, 2)}</code>
</pre>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'ID',
accessor: 'id',
},
{
Header: 'Name',
accessor: 'name',
},
{
Header: 'age',
accessor: 'age',
},
{
Header: 'gender',
accessor: 'gender',
},
{
Header: 'height',
accessor: 'height',
},
{
Header: 'color',
accessor: 'col',
},
{
Header: 'dob',
accessor: 'dob',
},
],
[]
)
return (
<Styles>
<Table columns={columns} />
</Styles>
)
}
function makeRow(id) {
let r = Math.floor(Math.random() * 3) + 1
if (r === 0) {
return {
Id: id,
name: 'Billy Bob',
age: 12,
gender: 'male',
height: 95,
col: 'red',
dob: '14/05/2010',
}
} else if (r === 1) {
return {
Id: id,
name: 'Jenny Jane',
age: 42,
gender: 'female',
height: 142,
col: 'blue',
dob: '30/07/1954',
}
} else if (r === 2) {
return {
Id: id,
name: 'Steve McAlistaire',
age: 35,
gender: 'male',
height: 176,
col: 'green',
dob: '04/11/1982',
}
} else if (r === 3) {
return {
Id: id,
name: 'Jeff Joe',
age: 35,
gender: 'male',
height: 176,
col: 'green',
dob: '04/11/1982',
}
}
}
export default App
+9
View File
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+6
View File
@@ -0,0 +1,6 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
ReactDOM.render(<App />, document.getElementById('root'))
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -57,7 +57,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
return (
<>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
<code>{JSON.stringify({ expanded: expanded }, null, 2)}</code>
</pre>
<table {...getTableProps()}>
<thead>
@@ -74,8 +74,8 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
prepareRow(row)
return (
// Use a React.Fragment here so the table markup is still valid
<>
<tr {...row.getRowProps()}>
<React.Fragment {...row.getRowProps()}>
<tr>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
@@ -100,7 +100,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
</td>
</tr>
) : null}
</>
</React.Fragment>
)
})}
</tbody>
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "react-table",
"version": "7.0.0-rc.1",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"version": "7.0.0-rc.11",
"description": "Hooks for building lightweight, fast and extendable datagrids for React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
"repository": {
+3 -73
View File
@@ -1,81 +1,11 @@
[
{
"timestamp": 1575605755429,
"timestamp": 1576640592762,
"files": [
{
"filename": "index.js",
"size": 21421,
"delta": 170
}
]
},
{
"timestamp": 1575579354616,
"files": [
{
"filename": "index.js",
"size": 21251,
"delta": 6
}
]
},
{
"timestamp": 1575578830463,
"files": [
{
"filename": "index.js",
"size": 21245,
"delta": 652
}
]
},
{
"timestamp": 1575555421868,
"files": [
{
"filename": "index.js",
"size": 20593,
"delta": 24
}
]
},
{
"timestamp": 1575517726476,
"files": [
{
"filename": "index.js",
"size": 20569,
"delta": 58
}
]
},
{
"timestamp": 1575391465436,
"files": [
{
"filename": "index.js",
"size": 20511,
"delta": 1
}
]
},
{
"timestamp": 1575345020328,
"files": [
{
"filename": "index.js",
"size": 20510,
"delta": 5
}
]
},
{
"timestamp": 1575331661254,
"files": [
{
"filename": "index.js",
"size": 20505,
"delta": 20505
"size": 22354,
"delta": 312
}
]
}
+3 -73
View File
@@ -1,81 +1,11 @@
[
{
"timestamp": 1575605764195,
"timestamp": 1576640599046,
"files": [
{
"filename": "index.es.js",
"size": 21200,
"delta": 170
}
]
},
{
"timestamp": 1575579366180,
"files": [
{
"filename": "index.es.js",
"size": 21030,
"delta": 7
}
]
},
{
"timestamp": 1575578837727,
"files": [
{
"filename": "index.es.js",
"size": 21023,
"delta": 575
}
]
},
{
"timestamp": 1575555429414,
"files": [
{
"filename": "index.es.js",
"size": 20448,
"delta": 21
}
]
},
{
"timestamp": 1575517715056,
"files": [
{
"filename": "index.es.js",
"size": 20427,
"delta": 59
}
]
},
{
"timestamp": 1575391457318,
"files": [
{
"filename": "index.es.js",
"size": 20368,
"delta": -1
}
]
},
{
"timestamp": 1575345027852,
"files": [
{
"filename": "index.es.js",
"size": 20369,
"delta": 4
}
]
},
{
"timestamp": 1575331668355,
"files": [
{
"filename": "index.es.js",
"size": 20365,
"delta": 20365
"size": 22153,
"delta": 305
}
]
}
+96 -81
View File
@@ -2,20 +2,63 @@ import React from 'react'
import {
actions,
reducerHandlers,
functionalUpdate,
mergeProps,
applyPropHooks,
useGetLatest,
useConsumeHookGetter,
makePropGetter,
} from '../utils'
const pluginName = 'useColumnVisibility'
actions.resetHiddenColumns = 'resetHiddenColumns'
actions.toggleHideColumn = 'toggleHideColumn'
actions.setHiddenColumns = 'setHiddenColumns'
actions.toggleHideAllColumns = 'toggleHideAllColumns'
reducerHandlers[pluginName] = (state, action) => {
export const useColumnVisibility = hooks => {
hooks.getToggleHiddenProps = [defaultGetToggleHiddenProps]
hooks.getToggleHideAllColumnsProps = [defaultGetToggleHideAllColumnsProps]
hooks.stateReducers.push(reducer)
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
hooks.headerGroupsDeps.push((deps, instance) => [
...deps,
instance.state.hiddenColumns,
])
hooks.useInstance.push(useInstance)
}
useColumnVisibility.pluginName = 'useColumnVisibility'
const defaultGetToggleHiddenProps = (props, instance, column) => [
props,
{
onChange: e => {
column.toggleHidden(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: column.isVisible,
title: 'Toggle Column Visible',
},
]
const defaultGetToggleHideAllColumnsProps = (props, instance) => [
props,
{
onChange: e => {
instance.toggleHideAllColumns(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: !instance.allColumnsHidden && !instance.state.hiddenColumns.length,
title: 'Toggle All Columns Hidden',
indeterminate:
!instance.allColumnsHidden && instance.state.hiddenColumns.length,
},
]
function reducer(state, action, previousState, instance) {
if (action.type === actions.init) {
return {
hiddenColumns: [],
@@ -26,7 +69,7 @@ reducerHandlers[pluginName] = (state, action) => {
if (action.type === actions.resetHiddenColumns) {
return {
...state,
hiddenColumns: [],
hiddenColumns: instance.initialState.hiddenColumns || [],
}
}
@@ -61,34 +104,27 @@ reducerHandlers[pluginName] = (state, action) => {
return {
...state,
hiddenColumns: shouldAll
? action.instanceRef.current.flatColumns.map(d => d.id)
: [],
hiddenColumns: shouldAll ? instance.flatColumns.map(d => d.id) : [],
}
}
}
export const useColumnVisibility = hooks => {
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => [
...deps,
instance.state.hiddenColumns,
])
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
hooks.useInstance.push(useInstance)
hooks.getToggleHiddenProps = []
hooks.getToggleHideAllColumnsProps = []
}
useColumnVisibility.pluginName = pluginName
function useInstanceBeforeDimensions(instance) {
const {
headers,
state: { hiddenColumns },
} = instance
const isMountedRef = React.useRef(false)
if (!isMountedRef.current) {
}
const handleColumn = (column, parentVisible) => {
column.isVisible = parentVisible && !hiddenColumns.includes(column.id)
column.isVisible =
typeof column.isVisible !== 'undefined'
? column.isVisible
: parentVisible && !hiddenColumns.includes(column.id)
let totalVisibleHeaderCount = 0
@@ -111,8 +147,6 @@ function useInstanceBeforeDimensions(instance) {
headers.forEach(
subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
)
return instance
}
function useInstance(instance) {
@@ -123,41 +157,10 @@ function useInstance(instance) {
state: { hiddenColumns },
} = instance
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const allColumnsHidden = flatColumns.length === hiddenColumns.length
flatHeaders.forEach(column => {
column.toggleHidden = value => {
dispatch({
type: actions.toggleHideColumn,
columnId: column.id,
value,
})
}
column.getToggleHiddenProps = props => {
return mergeProps(
{
onChange: e => {
column.toggleHidden(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: column.isVisible,
title: 'Toggle Column Visible',
},
applyPropHooks(
instanceRef.current.hooks.getToggleHiddenProps,
instanceRef.current
),
props
)
}
})
const toggleHideColumn = React.useCallback(
(columnId, value) =>
dispatch({ type: actions.toggleHideColumn, columnId, value }),
@@ -174,32 +177,44 @@ function useInstance(instance) {
[dispatch]
)
const getToggleHideAllColumnsProps = props => {
return mergeProps(
{
onChange: e => {
toggleHideAllColumns(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: !allColumnsHidden && !hiddenColumns.length,
title: 'Toggle All Columns Hidden',
indeterminate: !allColumnsHidden && hiddenColumns.length,
},
applyPropHooks(
instanceRef.current.hooks.getToggleHideAllColumnsProps,
instanceRef.current
),
props
)
}
// Snapshot hook and disallow more from being added
const getToggleHideAllColumnsPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleHideAllColumnsProps'
)
return {
...instance,
const getToggleHideAllColumnsProps = makePropGetter(
getToggleHideAllColumnsPropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getToggleHiddenPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleHiddenProps'
)
flatHeaders.forEach(column => {
column.toggleHidden = value => {
dispatch({
type: actions.toggleHideColumn,
columnId: column.id,
value,
})
}
column.getToggleHiddenProps = makePropGetter(
getToggleHiddenPropsHooks(),
getInstance(),
column
)
})
Object.assign(instance, {
allColumnsHidden,
toggleHideColumn,
setHiddenColumns,
toggleHideAllColumns,
getToggleHideAllColumnsProps,
}
})
}
+384 -305
View File
@@ -3,192 +3,195 @@ import React from 'react'
//
import {
actions,
reducerHandlers,
applyHooks,
applyPropHooks,
mergeProps,
flexRender,
reduceHooks,
loopHooks,
makePropGetter,
makeRenderer,
decorateColumnTree,
makeHeaderGroups,
flattenBy,
useGetLatest,
useConsumeHookGetter,
} from '../utils'
import makeDefaultPluginHooks from '../makeDefaultPluginHooks'
import { useColumnVisibility } from './useColumnVisibility'
let renderErr = 'Renderer Error'
if (process.env.NODE_ENV !== 'production') {
renderErr =
'You must specify a valid render component. This could be "column.Cell", "column.Header", "column.Filter", "column.Aggregated" or any other custom renderer component.'
}
const defaultInitialState = {}
const defaultColumnInstance = {}
const defaultReducer = (state, action, prevState) => state
const defaultGetSubRows = (row, index) => row.subRows || []
const defaultGetRowId = (row, index) => index
const defaultGetRowId = (row, index, parent) =>
`${parent ? [parent.id, index].join('.') : index}`
const defaultUseControlledState = d => d
export const useTable = (props, ...plugins) => {
// Destructure props
let {
data,
columns: userColumns,
function applyDefaults(props) {
const {
initialState = defaultInitialState,
defaultColumn = defaultColumnInstance,
getSubRows = defaultGetSubRows,
getRowId = defaultGetRowId,
reducer: userReducer = defaultReducer,
stateReducer = defaultReducer,
useControlledState = defaultUseControlledState,
debug,
...rest
} = props
return {
...rest,
initialState,
defaultColumn,
getSubRows,
getRowId,
stateReducer,
useControlledState,
}
}
export const useTable = (props, ...plugins) => {
// Apply default props
props = applyDefaults(props)
// Add core plugins
plugins = [useColumnVisibility, ...plugins]
debug = process.env.NODE_ENV === 'production' ? false : debug
const reducer = (state, action) => {
let nextState = Object.keys(reducerHandlers)
.map(key => reducerHandlers[key])
.reduce((state, handler) => handler(state, action) || state, state)
nextState = userReducer(nextState, action, state)
if (process.env.NODE_ENV !== 'production' && debug) {
console.info('')
console.info('React Table Action: ', action)
console.info('New State: ', nextState)
}
return nextState
}
// But use the users table state if provided
const [reducerState, originalDispatch] = React.useReducer(
reducer,
undefined,
() => reducer(initialState, { type: actions.init })
)
const state = useControlledState(reducerState)
// The table instance ref
// Create the table instance
let instanceRef = React.useRef({})
const dispatch = React.useCallback(action => {
if (!action.type) {
if (process.env.NODE_ENV !== 'production') {
console.info({ action })
throw new Error('Unknown Action Type! 👆')
}
throw new Error()
}
originalDispatch({ ...action, instanceRef })
}, [])
// Create a getter for the instance (helps avoid a lot of potential memory leaks)
const getInstance = useGetLatest(instanceRef.current)
Object.assign(instanceRef.current, {
// Assign the props, plugins and hooks to the instance
Object.assign(getInstance(), {
...props,
data, // The raw data
state, // The state dispatcher
dispatch, // The resolved table state
plugins, // All resolved plugins
hooks: {
columnsBeforeHeaderGroups: [],
columnsBeforeHeaderGroupsDeps: [],
useInstanceBeforeDimensions: [],
useInstance: [],
useRows: [],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getRowProps: [],
getHeaderGroupProps: [],
getFooterGroupProps: [],
getHeaderProps: [],
getFooterProps: [],
getCellProps: [],
},
plugins,
hooks: makeDefaultPluginHooks(),
})
// Allow plugins to register hooks
if (process.env.NODE_ENV !== 'production' && debug) console.time('plugins')
// Allow plugins to register hooks as early as possible
plugins.filter(Boolean).forEach(plugin => {
plugin(instanceRef.current.hooks)
plugin(getInstance().hooks)
})
if (process.env.NODE_ENV !== 'production' && debug) console.timeEnd('plugins')
const getUseOptionsHooks = useConsumeHookGetter(
getInstance().hooks,
'useOptions'
)
// Allow useOptions hooks to modify the options coming into the table
Object.assign(
getInstance(),
reduceHooks(getUseOptionsHooks(), applyDefaults(props))
)
const {
data,
columns: userColumns,
initialState,
defaultColumn,
getSubRows,
getRowId,
stateReducer,
useControlledState,
} = getInstance()
// Snapshot hook and disallow more from being added
const getStateReducers = useConsumeHookGetter(
getInstance().hooks,
'stateReducers'
)
// Setup user reducer ref
const getStateReducer = useGetLatest(stateReducer)
// Build the reducer
const reducer = React.useCallback(
(state, action) => {
// Detect invalid actions
if (!action.type) {
console.info({ action })
throw new Error('Unknown Action 👆')
}
// Reduce the state from all plugin reducers
return [
...getStateReducers(),
// Allow the user to add their own state reducer(s)
...(Array.isArray(getStateReducer())
? getStateReducer()
: [getStateReducer()]),
].reduce(
(s, handler) => handler(s, action, state, getInstance()) || s,
state
)
},
[getStateReducers, getStateReducer, getInstance]
)
// Start the reducer
const [reducerState, dispatch] = React.useReducer(reducer, undefined, () =>
reducer(initialState, { type: actions.init })
)
// Allow the user to control the final state with hooks
const state = useControlledState(reducerState)
Object.assign(getInstance(), {
state,
dispatch,
})
// Snapshot hook and disallow more from being added
const getColumnsHooks = useConsumeHookGetter(getInstance().hooks, 'columns')
// Snapshot hook and disallow more from being added
const getColumnsDepsHooks = useConsumeHookGetter(
getInstance().hooks,
'columnsDeps'
)
// Decorate All the columns
let columns = React.useMemo(
() => decorateColumnTree(userColumns, defaultColumn),
[defaultColumn, userColumns]
() =>
decorateColumnTree(
reduceHooks(getColumnsHooks(), userColumns, getInstance()),
defaultColumn
),
[
defaultColumn,
getColumnsHooks,
getInstance,
userColumns,
// eslint-disable-next-line react-hooks/exhaustive-deps
...reduceHooks(getColumnsDepsHooks(), [], getInstance()),
]
)
getInstance().columns = columns
// Get the flat list of all columns and allow hooks to decorate
// those columns (and trigger this memoization via deps)
let flatColumns = React.useMemo(() => {
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.columnsBeforeHeaderGroups')
let newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
flattenBy(columns, 'columns'),
instanceRef.current
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.columnsBeforeHeaderGroups')
return newColumns
}, [
let flatColumns = React.useMemo(() => flattenBy(columns, 'columns'), [
columns,
debug,
// eslint-disable-next-line react-hooks/exhaustive-deps
...applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
[],
instanceRef.current
),
])
// Make the headerGroups
const headerGroups = React.useMemo(
() => makeHeaderGroups(flatColumns, defaultColumn),
[defaultColumn, flatColumns]
)
const headers = React.useMemo(
() => (headerGroups.length ? headerGroups[0].headers : []),
[headerGroups]
)
Object.assign(instanceRef.current, {
columns,
flatColumns,
headerGroups,
headers,
})
getInstance().flatColumns = flatColumns
// Access the row model
const [rows, flatRows] = React.useMemo(() => {
if (process.env.NODE_ENV !== 'production' && debug)
console.time('getAccessedRows')
let flatRows = []
// Access the row's data
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
const accessRow = (originalRow, i, depth = 0, parent) => {
// Keep the original reference around
const original = originalRow
const rowId = getRowId(originalRow, i)
// Make the new path for the row
const path = [...parentPath, rowId]
const id = getRowId(originalRow, i, parent)
const row = {
id,
original,
index: i,
path, // used to create a key for each row even if not nested
depth,
cells: [{}], // This is a dummy cell
}
@@ -199,7 +202,7 @@ export const useTable = (props, ...plugins) => {
let subRows = getSubRows(originalRow, i)
if (subRows) {
row.subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, path))
row.subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, row))
}
// Override common array functions (and the dummy cell's getCellProps function)
@@ -216,9 +219,9 @@ export const useTable = (props, ...plugins) => {
// Create the cells and values
row.values = {}
flatColumns.forEach(column => {
row.values[column.id] = column.accessor
? column.accessor(originalRow, i, { subRows, depth, data })
flatColumns.forEach(({ id, accessor }) => {
row.values[id] = accessor
? accessor(originalRow, i, { subRows, depth, data })
: undefined
})
@@ -227,91 +230,161 @@ export const useTable = (props, ...plugins) => {
// Use the resolved data
const accessedData = data.map((d, i) => accessRow(d, i))
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('getAccessedRows')
return [accessedData, flatRows]
}, [debug, data, getRowId, getSubRows, flatColumns])
instanceRef.current.rows = rows
instanceRef.current.flatRows = flatRows
return [accessedData, flatRows]
}, [data, flatColumns, getRowId, getSubRows])
getInstance().rows = rows
getInstance().flatRows = flatRows
// Snapshot hook and disallow more from being added
const flatColumnsHooks = useConsumeHookGetter(
getInstance().hooks,
'flatColumns'
)
// Snapshot hook and disallow more from being added
const flatColumnsDepsHooks = useConsumeHookGetter(
getInstance().hooks,
'flatColumnsDeps'
)
// Get the flat list of all columns AFTER the rows
// have been access, and allow hooks to decorate
// those columns (and trigger this memoization via deps)
flatColumns = React.useMemo(
() => reduceHooks(flatColumnsHooks(), flatColumns, getInstance()),
[
flatColumns,
flatColumnsHooks,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
...reduceHooks(flatColumnsDepsHooks(), [], getInstance()),
]
)
getInstance().flatColumns = flatColumns
// Snapshot hook and disallow more from being added
const getHeaderGroups = useConsumeHookGetter(
getInstance().hooks,
'headerGroups'
)
// Snapshot hook and disallow more from being added
const getHeaderGroupsDeps = useConsumeHookGetter(
getInstance().hooks,
'headerGroupsDeps'
)
// Make the headerGroups
const headerGroups = React.useMemo(
() =>
reduceHooks(
getHeaderGroups(),
makeHeaderGroups(flatColumns, defaultColumn),
getInstance()
),
[
defaultColumn,
flatColumns,
getHeaderGroups,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
...reduceHooks(getHeaderGroupsDeps(), [], getInstance()),
]
)
getInstance().headerGroups = headerGroups
const headers = React.useMemo(
() => (headerGroups.length ? headerGroups[0].headers : []),
[headerGroups]
)
getInstance().headers = headers
// Provide a flat header list for utilities
instanceRef.current.flatHeaders = headerGroups.reduce(
getInstance().flatHeaders = headerGroups.reduce(
(all, headerGroup) => [...all, ...headerGroup.headers],
[]
)
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useInstanceBeforeDimensions')
instanceRef.current = applyHooks(
instanceRef.current.hooks.useInstanceBeforeDimensions,
instanceRef.current
// Snapshot hook and disallow more from being added
const getUseInstanceBeforeDimensions = useConsumeHookGetter(
getInstance().hooks,
'useInstanceBeforeDimensions'
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.useInstanceBeforeDimensions')
loopHooks(getUseInstanceBeforeDimensions(), getInstance())
// Header Visibility is needed by this point
calculateDimensions(instanceRef.current)
const [
totalColumnsMinWidth,
totalColumnsWidth,
totalColumnsMaxWidth,
] = calculateHeaderWidths(headers)
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useInstance')
instanceRef.current = applyHooks(
instanceRef.current.hooks.useInstance,
instanceRef.current
getInstance().totalColumnsMinWidth = totalColumnsMinWidth
getInstance().totalColumnsWidth = totalColumnsWidth
getInstance().totalColumnsMaxWidth = totalColumnsMaxWidth
// Snapshot hook and disallow more from being added
const getUseInstance = useConsumeHookGetter(
getInstance().hooks,
'useInstance'
)
loopHooks(getUseInstance(), getInstance())
// Snapshot hook and disallow more from being added
const getHeaderPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getHeaderProps'
)
// Snapshot hook and disallow more from being added
const getFooterPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getFooterProps'
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.useInstance')
// Each materialized header needs to be assigned a render function and other
// prop getter properties here.
instanceRef.current.flatHeaders.forEach(column => {
// Give columns/headers rendering power
column.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
;[...getInstance().flatHeaders, ...getInstance().flatColumns].forEach(
column => {
// Give columns/headers rendering power
column.render = makeRenderer(getInstance(), column)
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
// Give columns/headers a default getHeaderProps
column.getHeaderProps = makePropGetter(
getHeaderPropsHooks(),
getInstance(),
column
)
return flexRender(Comp, {
...instanceRef.current,
column,
...userProps,
})
// Give columns/headers a default getFooterProps
column.getFooterProps = makePropGetter(
getFooterPropsHooks(),
getInstance(),
column
)
}
)
// Give columns/headers a default getHeaderProps
column.getHeaderProps = props =>
mergeProps(
{
key: ['header', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
},
applyPropHooks(
instanceRef.current.hooks.getHeaderProps,
column,
instanceRef.current
),
props
)
// Snapshot hook and disallow more from being added
const getHeaderGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getHeaderGroupProps'
)
// Give columns/headers a default getFooterProps
column.getFooterProps = props =>
mergeProps(
{
key: ['footer', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
},
applyPropHooks(
instanceRef.current.hooks.getFooterProps,
column,
instanceRef.current
),
props
)
})
// Snapshot hook and disallow more from being added
const getFooterGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getFooterGroupProps'
)
instanceRef.current.headerGroups = instanceRef.current.headerGroups.filter(
getInstance().headerGroups = getInstance().headerGroups.filter(
(headerGroup, i) => {
// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers = headerGroup.headers.filter(column => {
@@ -330,31 +403,19 @@ export const useTable = (props, ...plugins) => {
// Give headerGroups getRowProps
if (headerGroup.headers.length) {
headerGroup.getHeaderGroupProps = (props = {}) =>
mergeProps(
{
key: [`header${i}`].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getHeaderGroupProps,
headerGroup,
instanceRef.current
),
props
)
headerGroup.getHeaderGroupProps = makePropGetter(
getHeaderGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
headerGroup.getFooterGroupProps = (props = {}) =>
mergeProps(
{
key: [`footer${i}`].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getFooterGroupProps,
headerGroup,
instanceRef.current
),
props
)
headerGroup.getFooterGroupProps = makePropGetter(
getFooterGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
return true
}
@@ -363,40 +424,49 @@ export const useTable = (props, ...plugins) => {
}
)
instanceRef.current.footerGroups = [
...instanceRef.current.headerGroups,
].reverse()
getInstance().footerGroups = [...getInstance().headerGroups].reverse()
// Run the rows (this could be a dangerous hook with a ton of data)
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useRows')
instanceRef.current.rows = applyHooks(
instanceRef.current.hooks.useRows,
instanceRef.current.rows,
instanceRef.current
// Snapshot hook and disallow more from being added
const getUseRowsHooks = useConsumeHookGetter(getInstance().hooks, 'useRows')
getInstance().rows = reduceHooks(
getUseRowsHooks(),
getInstance().rows,
getInstance()
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.useRows')
// The prepareRow function is absolutely necessary and MUST be called on
// any rows the user wishes to be displayed.
instanceRef.current.prepareRow = React.useCallback(row => {
row.getRowProps = props =>
mergeProps(
{ key: ['row', ...row.path].join('_') },
applyPropHooks(
instanceRef.current.hooks.getRowProps,
row,
instanceRef.current
),
props
)
// Snapshot hook and disallow more from being added
const getPrepareRowHooks = useConsumeHookGetter(
getInstance().hooks,
'prepareRow'
)
// Build the visible cells for each row
row.cells = instanceRef.current.flatColumns
.filter(d => d.isVisible)
.map(column => {
// Snapshot hook and disallow more from being added
const getRowPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getRowProps'
)
// Snapshot hook and disallow more from being added
const getCellPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getCellProps'
)
// Snapshot hook and disallow more from being added
const cellsHooks = useConsumeHookGetter(getInstance().hooks, 'cells')
getInstance().prepareRow = React.useCallback(
row => {
row.getRowProps = makePropGetter(getRowPropsHooks(), getInstance(), row)
// Build the visible cells for each row
row.allCells = flatColumns.map(column => {
const cell = {
column,
row,
@@ -404,74 +474,73 @@ export const useTable = (props, ...plugins) => {
}
// Give each cell a getCellProps base
cell.getCellProps = props => {
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getCellProps,
cell,
instanceRef.current
),
props
)
}
cell.getCellProps = makePropGetter(
getCellPropsHooks(),
getInstance(),
cell
)
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
column,
row,
cell,
...userProps,
})
}
cell.render = makeRenderer(getInstance(), column, {
row,
cell,
})
return cell
})
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
}, [])
row.cells = reduceHooks(cellsHooks(), row.allCells, getInstance())
instanceRef.current.getTableProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableProps,
instanceRef.current
),
userProps
)
// need to apply any row specific hooks (useExpanded requires this)
loopHooks(getPrepareRowHooks(), row, getInstance())
},
[
getRowPropsHooks,
getInstance,
flatColumns,
cellsHooks,
getPrepareRowHooks,
getCellPropsHooks,
]
)
instanceRef.current.getTableBodyProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableBodyProps,
instanceRef.current
),
userProps
)
// Snapshot hook and disallow more from being added
const getTablePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getTableProps'
)
return instanceRef.current
}
getInstance().getTableProps = makePropGetter(
getTablePropsHooks(),
getInstance()
)
function calculateDimensions(instance) {
const { headers } = instance
// Snapshot hook and disallow more from being added
const getTableBodyPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getTableBodyProps'
)
instance.totalColumnsWidth = calculateHeaderWidths(headers)
getInstance().getTableBodyProps = makePropGetter(
getTableBodyPropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getUseFinalInstanceHooks = useConsumeHookGetter(
getInstance().hooks,
'useFinalInstance'
)
loopHooks(getUseFinalInstanceHooks(), getInstance())
return getInstance()
}
function calculateHeaderWidths(headers, left = 0) {
let sumTotalMinWidth = 0
let sumTotalWidth = 0
let sumTotalMaxWidth = 0
headers.forEach(header => {
let { headers: subHeaders } = header
@@ -479,18 +548,28 @@ function calculateHeaderWidths(headers, left = 0) {
header.totalLeft = left
if (subHeaders && subHeaders.length) {
header.totalWidth = calculateHeaderWidths(subHeaders, left)
const [totalMinWidth, totalWidth, totalMaxWidth] = calculateHeaderWidths(
subHeaders,
left
)
header.totalMinWidth = totalMinWidth
header.totalWidth = totalWidth
header.totalMaxWidth = totalMaxWidth
} else {
header.totalMinWidth = header.minWidth
header.totalWidth = Math.min(
Math.max(header.minWidth, header.width),
header.maxWidth
)
header.totalMaxWidth = header.maxWidth
}
if (header.isVisible) {
left += header.totalWidth
sumTotalMinWidth += header.totalMinWidth
sumTotalWidth += header.totalWidth
sumTotalMaxWidth += header.totalMaxWidth
}
})
return sumTotalWidth
return [sumTotalMinWidth, sumTotalWidth, sumTotalMaxWidth]
}
+2 -1
View File
@@ -1,4 +1,4 @@
export * from './utils'
export * from './publicUtils'
export { useTable } from './hooks/useTable'
export { useExpanded } from './plugin-hooks/useExpanded'
export { useFilters } from './plugin-hooks/useFilters'
@@ -11,3 +11,4 @@ export { useColumnOrder } from './plugin-hooks/useColumnOrder'
export { useResizeColumns } from './plugin-hooks/useResizeColumns'
export { useAbsoluteLayout } from './plugin-hooks/useAbsoluteLayout'
export { useBlockLayout } from './plugin-hooks/useBlockLayout'
export { useFlexLayout } from './plugin-hooks/useFlexLayout'
+60
View File
@@ -0,0 +1,60 @@
const defaultCells = cell => cell.filter(d => d.column.isVisible)
const defaultGetHeaderProps = (props, instance, column) => ({
key: `header_${column.id}`,
colSpan: column.totalVisibleHeaderCount,
...props,
})
const defaultGetFooterProps = (props, instance, column) => ({
key: `footer_${column.id}`,
colSpan: column.totalVisibleHeaderCount,
...props,
})
const defaultGetHeaderGroupProps = (props, instance, headerGroup, index) => ({
key: `headerGroup_${index}`,
...props,
})
const defaultGetFooterGroupProps = (props, instance, headerGroup, index) => ({
key: `footerGroup_${index}`,
...props,
})
const defaultGetRowProps = (props, instance, row) => ({
key: `row_${row.id}`,
...props,
})
const defaultGetCellProps = (props, instance, cell) => ({
...props,
key: `cell_${cell.row.id}_${cell.column.id}`,
})
export default function makeDefaultPluginHooks() {
return {
useOptions: [],
stateReducers: [],
columns: [],
columnsDeps: [],
flatColumns: [],
flatColumnsDeps: [],
headerGroups: [],
headerGroupsDeps: [],
useInstanceBeforeDimensions: [],
useInstance: [],
useRows: [],
cells: [defaultCells],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getHeaderGroupProps: [defaultGetHeaderGroupProps],
getFooterGroupProps: [defaultGetFooterGroupProps],
getHeaderProps: [defaultGetHeaderProps],
getFooterProps: [defaultGetFooterProps],
getRowProps: [defaultGetRowProps],
getCellProps: [defaultGetCellProps],
useFinalInstance: [],
}
}
@@ -10,10 +10,10 @@ Snapshot Diff:
<pre>
<code>
{
- "expanded": []
+ "expanded": [
+ "0"
+ ]
- "expanded": {}
+ "expanded": {
+ "0": true
+ }
}
</code>
</pre>
@@ -161,11 +161,11 @@ Snapshot Diff:
<pre>
<code>
{
"expanded": [
- "0"
+ "0",
+ "0.0"
]
"expanded": {
- "0": true
+ "0": true,
+ "0.0": true
}
}
</code>
</pre>
@@ -311,12 +311,12 @@ Snapshot Diff:
<pre>
<code>
{
"expanded": [
"0",
- "0.0"
+ "0.0",
+ "0.0.0"
]
"expanded": {
"0": true,
- "0.0": true
+ "0.0": true,
+ "0.0.0": true
}
}
</code>
</pre>
@@ -461,13 +461,13 @@ Snapshot Diff:
@@ -3,11 +3,12 @@
<code>
{
"expanded": [
"0",
"0.0",
- "0.0.0"
+ "0.0.0",
+ "0.0.0.0"
]
"expanded": {
"0": true,
"0.0": true,
- "0.0.0": true
+ "0.0.0": true,
+ "0.0.0.0": true
}
}
</code>
</pre>
@@ -528,13 +528,13 @@ Snapshot Diff:
<pre>
<code>
{
- "expanded": [
- "0",
- "0.0",
- "0.0.0",
- "0.0.0.0"
- ]
+ "expanded": []
- "expanded": {
- "0": true,
- "0.0": true,
- "0.0.0": true,
- "0.0.0.0": true
- }
+ "expanded": {}
}
</code>
</pre>
@@ -485,45 +485,45 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": []
+ "selectedRowPaths": [
+ "0",
+ "1",
+ "2",
+ "2.0",
+ "2.1",
+ "3",
+ "4",
+ "5",
+ "6",
+ "6.0",
+ "6.1",
+ "7",
+ "8",
+ "9",
+ "10",
+ "10.0",
+ "10.1",
+ "11",
+ "12",
+ "13",
+ "14",
+ "14.0",
+ "14.1",
+ "15",
+ "16",
+ "17",
+ "18",
+ "18.0",
+ "18.1",
+ "19",
+ "20",
+ "21",
+ "22",
+ "22.0",
+ "22.1",
+ "23"
+ ]
- "selectedRowIds": {}
+ "selectedRowIds": {
+ "0": true,
+ "1": true,
+ "2": true,
+ "3": true,
+ "4": true,
+ "5": true,
+ "6": true,
+ "7": true,
+ "8": true,
+ "9": true,
+ "10": true,
+ "11": true,
+ "12": true,
+ "13": true,
+ "14": true,
+ "15": true,
+ "16": true,
+ "17": true,
+ "18": true,
+ "19": true,
+ "20": true,
+ "21": true,
+ "22": true,
+ "23": true,
+ "2.0": true,
+ "2.1": true,
+ "6.0": true,
+ "6.1": true,
+ "10.0": true,
+ "10.1": true,
+ "14.0": true,
+ "14.1": true,
+ "18.0": true,
+ "18.1": true,
+ "22.0": true,
+ "22.1": true
+ }
}
</code>
</pre>
@@ -1015,45 +1015,45 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": [
- "0",
- "1",
- "2",
- "2.0",
- "2.1",
- "3",
- "4",
- "5",
- "6",
- "6.0",
- "6.1",
- "7",
- "8",
- "9",
- "10",
- "10.0",
- "10.1",
- "11",
- "12",
- "13",
- "14",
- "14.0",
- "14.1",
- "15",
- "16",
- "17",
- "18",
- "18.0",
- "18.1",
- "19",
- "20",
- "21",
- "22",
- "22.0",
- "22.1",
- "23"
- ]
+ "selectedRowPaths": []
- "selectedRowIds": {
- "0": true,
- "1": true,
- "2": true,
- "3": true,
- "4": true,
- "5": true,
- "6": true,
- "7": true,
- "8": true,
- "9": true,
- "10": true,
- "11": true,
- "12": true,
- "13": true,
- "14": true,
- "15": true,
- "16": true,
- "17": true,
- "18": true,
- "19": true,
- "20": true,
- "21": true,
- "22": true,
- "23": true,
- "2.0": true,
- "2.1": true,
- "6.0": true,
- "6.1": true,
- "10.0": true,
- "10.1": true,
- "14.0": true,
- "14.1": true,
- "18.0": true,
- "18.1": true,
- "22.0": true,
- "22.1": true
- }
+ "selectedRowIds": {}
}
</code>
</pre>
@@ -1129,13 +1129,13 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": []
+ "selectedRowPaths": [
+ "0",
+ "2",
+ "2.0",
+ "2.1"
+ ]
- "selectedRowIds": {}
+ "selectedRowIds": {
+ "0": true,
+ "2": true,
+ "2.0": true,
+ "2.1": true
+ }
}
</code>
</pre>
@@ -1198,13 +1198,13 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
- "0",
- "2",
- "2.0",
- "2.1"
+ "0"
]
"selectedRowIds": {
- "0": true,
- "2": true,
- "2.0": true,
- "2.1": true
+ "0": true
}
}
</code>
</pre>
@@ -1241,11 +1241,11 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
- "0"
+ "0",
+ "2.0"
]
"selectedRowIds": {
- "0": true
+ "0": true,
+ "2.0": true
}
}
</code>
</pre>
@@ -1257,6 +1257,19 @@ Snapshot Diff:
- First value
+ Second value
@@ -163,11 +163,11 @@
</label>
</div>
</td>
<td>
<div>
- Row 2 Not Selected
+ Row 2 Selected
</div>
</td>
<td>
joe
</td>
@@ -237,11 +237,11 @@
</label>
</div>
@@ -1282,12 +1295,12 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"0",
- "2.0"
+ "2.0",
+ "2.1"
]
"selectedRowIds": {
"0": true,
- "2.0": true
+ "2.0": true,
+ "2.1": true
}
}
</code>
</pre>
@@ -1299,6 +1312,19 @@ Snapshot Diff:
- First value
+ Second value
@@ -163,11 +163,11 @@
</label>
</div>
</td>
<td>
<div>
- Row 2 Selected
+ Row 2 Not Selected
</div>
</td>
<td>
joe
</td>
@@ -237,11 +237,11 @@
</label>
</div>
@@ -1324,12 +1350,12 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"0",
- "2.0",
- "2.1"
+ "2.0"
]
"selectedRowIds": {
"0": true,
- "2.0": true,
- "2.1": true
+ "2.0": true
}
}
</code>
</pre>
+1 -1
View File
@@ -64,7 +64,7 @@ function Table({ columns: userColumns, data, SubComponent }) {
return (
<>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
<code>{JSON.stringify({ expanded: expanded }, null, 2)}</code>
</pre>
<table {...getTableProps()}>
<thead>
+47 -34
View File
@@ -75,14 +75,43 @@ function Table({ columns, data }) {
headerGroups,
rows,
prepareRow,
state: { selectedRowPaths },
state: { selectedRowIds },
} = useTable(
{
columns,
data,
},
useRowSelect,
useExpanded
useExpanded,
hooks => {
hooks.flatColumns.push(columns => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<label>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />{' '}
Select All
</label>
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<label>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />{' '}
Select Row
</label>
</div>
),
},
...columns,
])
}
)
// Render the UI for your table
@@ -113,53 +142,37 @@ function Table({ columns, data }) {
)}
</tbody>
</table>
<p>Selected Rows: {selectedRowPaths.size}</p>
<p>Selected Rows: {Object.keys(selectedRowIds).length}</p>
<pre>
<code>
{JSON.stringify(
{ selectedRowPaths: [...selectedRowPaths.values()] },
null,
2
)}
{JSON.stringify({ selectedRowIds: selectedRowIds }, null, 2)}
</code>
</pre>
</>
)
}
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return <input type="checkbox" ref={resolvedRef} {...rest} />
}
)
function App() {
const columns = React.useMemo(
() => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<label>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />{' '}
Select All
</label>
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<label>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />{' '}
Select Row
</label>
</div>
),
},
{
id: 'selectedStatus',
Cell: ({ row }) => (
<div>
Row {row.path.join('.')}{' '}
{row.isSelected ? 'Selected' : 'Not Selected'}
Row {row.id} {row.isSelected ? 'Selected' : 'Not Selected'}
</div>
),
},
+37 -41
View File
@@ -1,57 +1,53 @@
export const useAbsoluteLayout = hooks => {
hooks.useInstance.push(useInstance)
import { ensurePluginOrder } from '../utils'
const cellStyles = {
position: 'absolute',
top: 0,
}
useAbsoluteLayout.pluginName = 'useAbsoluteLayout'
export const useAbsoluteLayout = hooks => {
hooks.getTableBodyProps.push(getRowStyles)
hooks.getRowProps.push(getRowStyles)
hooks.getHeaderGroupProps.push(getRowStyles)
hooks.useInstance.push(useInstance)
const useInstance = instance => {
const {
totalColumnsWidth,
hooks: {
getRowProps,
getTableBodyProps,
getHeaderGroupProps,
getHeaderProps,
getCellProps,
},
} = instance
const rowStyles = {
style: {
position: 'relative',
width: `${totalColumnsWidth}px`,
},
}
getTableBodyProps.push(() => rowStyles)
getRowProps.push(() => rowStyles)
getHeaderGroupProps.push(() => rowStyles)
// Calculating column/cells widths
const cellStyles = {
position: 'absolute',
top: 0,
}
getHeaderProps.push(header => {
return {
hooks.getHeaderProps.push((props, instance, header) => [
props,
{
style: {
...cellStyles,
left: `${header.totalLeft}px`,
width: `${header.totalWidth}px`,
},
}
})
},
])
getCellProps.push(cell => {
return {
hooks.getCellProps.push((props, instance, cell) => [
props,
{
style: {
...cellStyles,
left: `${cell.column.totalLeft}px`,
width: `${cell.column.totalWidth}px`,
},
}
})
},
])
}
return instance
useAbsoluteLayout.pluginName = 'useAbsoluteLayout'
const getRowStyles = (props, instance) => [
props,
{
style: {
position: 'relative',
width: `${instance.totalColumnsWidth}px`,
},
},
]
function useInstance({ plugins }) {
ensurePluginOrder(plugins, [], useAbsoluteLayout.pluginName, [
'useResizeColumns',
])
}
+24 -30
View File
@@ -1,47 +1,41 @@
export const useBlockLayout = hooks => {
hooks.useInstance.push(useInstance)
const cellStyles = {
display: 'inline-block',
boxSizing: 'border-box',
}
useBlockLayout.pluginName = 'useBlockLayout'
const useInstance = instance => {
const {
totalColumnsWidth,
hooks: { getRowProps, getHeaderGroupProps, getHeaderProps, getCellProps },
} = instance
const rowStyles = {
const getRowStyles = (props, instance) => [
props,
{
style: {
display: 'flex',
width: `${totalColumnsWidth}px`,
width: `${instance.totalColumnsWidth}px`,
},
}
},
]
getRowProps.push(() => rowStyles)
getHeaderGroupProps.push(() => rowStyles)
export const useBlockLayout = hooks => {
hooks.getRowProps.push(getRowStyles)
hooks.getHeaderGroupProps.push(getRowStyles)
const cellStyles = {
display: 'inline-block',
boxSizing: 'border-box',
}
getHeaderProps.push(header => {
return {
hooks.getHeaderProps.push((props, instance, header) => [
props,
{
style: {
...cellStyles,
width: `${header.totalWidth}px`,
},
}
})
},
])
getCellProps.push(cell => {
return {
hooks.getCellProps.push((props, instance, cell) => [
props,
{
style: {
...cellStyles,
width: `${cell.column.totalWidth}px`,
},
}
})
return instance
},
])
}
useBlockLayout.pluginName = 'useBlockLayout'

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