Compare commits

...
66 Commits
Author SHA1 Message Date
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
Tanner Linsley a152704fde v7.0.0-rc.1 2019-12-05 23:36:14 -05:00
Tanner Linsley 32033b7095 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-05 23:19:38 -05:00
Tanner Linsley f73d87ac5d v7.0.0-rc.0
Fixes #1573
Fixes #1719
Fixes #1718
2019-12-05 23:18:48 -05:00
dependabot[bot]andTanner Linsley b92e25c21a Bump eslint-utils from 1.4.0 to 1.4.3 in /examples/basic (#1720)
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-05 23:17:00 -05:00
size-plugin[bot]andGitHub 536217e430 ⛹🏿‍♂️ 🦻🏻 update sizes-es.json 👍 2019-12-06 04:16:18 +00:00
size-plugin[bot]andGitHub d038c6e781 😒 🐜 update sizes-cjs.json 👍 2019-12-06 04:16:17 +00:00
Tanner Linsley 438ce81fc5 Update API doc links 2019-12-05 23:14:23 -05:00
Tanner Linsley 7a0688aa63 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-05 23:14:17 -05:00
Tanner Linsley a33a008608 Add Footer Support 2019-12-05 23:11:50 -05:00
size-plugin[bot]andGitHub 67dd1d23b1 🕓 😞 update sizes-cjs.json 👍 2019-12-05 20:56:38 +00:00
size-plugin[bot]andGitHub 4aad402644 📸 🤟🏼 update sizes-es.json 👍 2019-12-05 20:56:37 +00:00
Tanner Linsley 75acd4a35b Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-05 15:51:30 -05:00
Tanner Linsley a170d33956 7.0.0-beta.28 2019-12-05 15:51:09 -05:00
size-plugin[bot]andGitHub 4c9d868a12 🧜🏽‍♀️ 🧖‍♀️ update sizes-cjs.json 👍 2019-12-05 20:48:59 +00:00
size-plugin[bot]andGitHub 08d6e2da71 🦽 🟪 update sizes-es.json 👍 2019-12-05 20:48:58 +00:00
Martin BrennerandTanner Linsley 7169b3100b Remove tooltip if columnDisableSortBy (#1685)
* Remove tooltip if columnDisableSortBy

* update sorting test snapshot
2019-12-05 15:48:57 -05:00
dependabot[bot]andTanner Linsley e5d672b9ea Bump eslint-utils from 1.4.0 to 1.4.3 in /examples/column-hiding (#1717)
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-05 15:48:41 -05:00
Tanner LinsleyandGitHub 8ba553871f Add useColumnVisibility as core hook (#1700)
* Update utils.js

* Update useTable.js

* Create useColumnVisibility.js

* Update useColumnVisibility.js

* Update useColumnVisibility.js

* Convert to core hook, use new reducerHanndler/actions

* Add useColumnVisibility internal hook
2019-12-05 15:45:25 -05:00
Tanner LinsleyandGitHub 3097997734 Merge 9727202b14 into master 2019-12-05 09:18:01 -05:00
Tanner Linsley 9727202b14 Update Example 2019-12-05 09:17:59 -05:00
size-plugin[bot]andGitHub 6cb52cc3a6 🤦🏽‍♀️ 🦑 update sizes-cjs.json 👍 2019-12-05 14:17:13 +00:00
size-plugin[bot]andGitHub ee4f3f1d75 🇳🇮 🈚️ update sizes-es.json 👍 2019-12-05 14:17:12 +00:00
Martin BrennerandTanner Linsley 487abd2119 pass the instance with updated rows (#1714) 2019-12-05 09:14:07 -05:00
90 changed files with 24186 additions and 2266 deletions
+27 -8
View File
@@ -1,20 +1,39 @@
{
"dist/index.js": {
"bundled": 97093,
"minified": 46881,
"gzipped": 12344
"bundled": 108216,
"minified": 51347,
"gzipped": 13498
},
"dist/index.es.js": {
"bundled": 96528,
"minified": 46389,
"gzipped": 12228,
"bundled": 107373,
"minified": 50597,
"gzipped": 13345,
"treeshaked": {
"rollup": {
"code": 78,
"code": 80,
"import_statements": 21
},
"webpack": {
"code": 11143
"code": 8904
}
}
},
"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
}
}
}
+83
View File
@@ -1,3 +1,85 @@
## 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 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)
## 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
## 7.0.0-rc.0
- Added the support for the `Footer` renderer, `column.getFooterProps`, `footerGroups` and `footerGroup.getFooterProps`
## 7.0.0-beta.28
- Added the `useColumnVisibility` plugin as a core plugin along with several new instance and column-level methods to control column visibility
- Added the "column-hiding" example
## 7.0.0-beta.27
- Added the `useControlledState` option, which allows for hook-context control of the resolved internal table state
@@ -6,6 +88,7 @@
- Fixed an issue where the table would crash if useSortBy was reset via the resetSortBy action
- Updated all of the examples to use the "react-table@latest" tag.
- `utils` is no longer an exported variable and instead, all of the individual util methods are exported at the root level of the library.
## 7.0.0-beta.25
+3 -3
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,14 +35,13 @@ 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
- [Installation](./docs/installation.md) - Walk through how to install React Table
- [Concepts](./docs/concepts.md) - Read how React Table works and how you can use it better
- [Examples](./docs/examples.md) - Experience and learn from some examples and guides of how to use React Table and implement common patterns
- [API](./docs/api.md) - Get to know React Table's API
- [API](./docs/api/README.md) - Get to know React Table's API
- [FAQ](./docs/faq.md) - Learn how to use React Table for specific challenges and tasks
- [Previous Versions](#previous-versions)
- [Contributing](./CONTRIBUTING.md) - Become familiar with how to contribute back to React Table
@@ -182,6 +181,7 @@ This library is being built and maintained by me, @tannerlinsley and I am always
<li>Jordan Soltman</li>
<li>Robert Tajnšek</li>
<li>Pekka Tapani</li>
<li>Eric Lanehart (@pushred)</li>
</ul>
</td>
<td>
-1111
View File
File diff suppressed because it is too large Load Diff
+66
View File
@@ -0,0 +1,66 @@
# API
React Table uses React Hooks both internally and externally for almost all of its configuration and lifecycle management. Naturally, this is what allows React Table to be headless and lightweight while still having a concise and simple API.
React Table is essentially a compatible collection of **custom React hooks**:
- The primary React Table hook
- [`useTable`](./useTable.md)
- Plugin Hooks
- Core Plugin Hooks
- [`useGroupBy`](./useGroupBy.md)
- [`useFilters`](./useFilters.md)
- [`useSortBy`](./useSortBy.md)
- [`useExpanded`](./useExpanded.md)
- [`usePagination`](./usePagination.md)
- [`useTokenPagination` (Coming Soon)](./useTokenPagination.md)
- [`useRowSelect`](./useRowSelect.md)
- [`useRowState`](./useRowState.md)
- [`useColumnOrder`](./useColumnOrder.md)
- Layout Hooks
- [`useBlockLayout`](./useBlockLayout.md)
- [`useAbsoluteLayout`](./useAbsoluteLayout.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)
### Hook Usage
`useTable` is the **primary** hook used to build a React Table. It serves as the starting point for **every option and every plugin hook** that React Table supports. The options passed into `useTable` are supplied to every plugin hook after it in the order they are supplied, eventually resulting in a final `instance` object that you can use to build your table UI and interact with the table's state.
```js
const instance = useTable(
{
data: [...],
columns: [...],
},
useGroupBy,
useFilters,
useSortBy,
useExpanded,
usePagination
)
```
### The stages of React Table and plugins
1. `useTable` is called. A table instance is created.
1. The `instance.state` is resolved from either a custom user state or an automatically generated one.
1. A collection of plugin points is created at `instance.hooks`.
1. Each plugin is given the opportunity to add hooks to `instance.hook`.
1. As the `useTable` logic proceeds to run, each plugin hook type is used at a specific point in time with each individual hook function being executed the order it was registered.
1. The final instance object is returned from `useTable`, which the developer then uses to construct their table.
This multi-stage process is the secret sauce that allows React Table plugin hooks to work together and compose nicely, while not stepping on each others toes.
To dive deeper into plugins, see Plugins](TODO) and the [Plugin Guide
### Plugin Hook Order & Consistency
The order and usage of plugin hooks must follow The Laws of Hooks, just like any other custom hook. They must always be unconditionally called in the same order.
> **NOTE: In the event that you want to programmatically enable or disable plugin hooks, most of them provide options to disable their functionality, eg. `options.disableSortBy`**
### Option Memoization
React Table relies on memoization to determine when state and side effects should update or be calculated. This means that every option you pass to `useTable` should be memoized either via `React.useMemo` (for objects) or `React.useCallback` (for functions).
+37
View File
@@ -0,0 +1,37 @@
# `useAbsoluteLayout`
- Plugin Hook
- Optional
`useAbsoluteLayout` is a plugin hook that adds support for headers and cells to be rendered as absolutely positioned `div`s (or other non-table elements) with explicit `width`. Similar to the `useBlockLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
**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. [See Column Options](#column-options) for more information on these options.
### Instance Properties
- `getTableBodyProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for the table body
### 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
### Header Properties
- `getHeaderProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/absolute-layout)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/absolute-layout)
+31
View File
@@ -0,0 +1,31 @@
# `useBlocklayout`
- Plugin Hook
- Optional
`useBlocklayout` 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 explicit `width`. Similar to the `useAbsoluteLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
**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. [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
### Header Properties
- `getHeaderProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/block-layout)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/block-layout)
+29
View File
@@ -0,0 +1,29 @@
# `useColumnOrder`
- Plugin Hook
- Optional
`useColumnOrder` is a plugin hook that implements **basic column reordering**. As columns are reordered, their header groups are reverse-engineered so as to never have orphaned header groups.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.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
The following values are provided to the table `instance`:
- `setColumnOrder: Function(updater: Function | Array<ColumnId>) => void`
- Use this function to programmatically update the columnOrder.
- `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.
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
+60
View File
@@ -0,0 +1,60 @@
# `useExpanded`
- Plugin Hook
- Optional
`useExpanded` is the hook that implements **row expanding**. It is most often used with `useGroupBy` to expand grouped rows or on its own with nested `subRows` in tree-like `data` sets, but is not limited to these use-cases. It supports expanding rows both via internal table state and also via a hard-coded key on the raw row model.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.expanded: Array<pathKey: String>`
- 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.
- 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
- `manualExpandedKey: String`
- Optional
- Defaults to `expanded`
- This string is used as the key to detect manual expanded state on any given row. For example, if a raw data row like `{ name: 'Tanner Linsley', friends: [...], expanded: true}` was detected, it would always be expanded, regardless of state.
- `expandSubRows: Bool`
- Optional
- 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.
- `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.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.
### Row Properties
The following additional properties are available on every `row` object returned by the table instance.
- `isExpanded: Bool`
- If `true`, this row is in an expanded state.
- `toggleExpanded: Function(?isExpanded: Bool) => void`
- This function will toggle the expanded state of a row between `true` and `false` or, if an `isExpanded` boolean is passed to the function, it will be set as the new `isExpanded` value.
- Rows with a hard-coded `manualExpandedKey` (defaults to `expanded`) set to `true` are not affected by this function or the internal expanded state.
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/expanding)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/expanding)
+96
View File
@@ -0,0 +1,96 @@
# `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
- `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)
+120
View File
@@ -0,0 +1,120 @@
# `useGroupBy`
- Plugin Hook
- Optional
`useGroupBy` is the hook that implements **row grouping and aggregation**.
- Each column's `getGroupByToggleProps()` function can be used to generate the props needed to make a clickable UI element that will toggle the grouping on or off for a specific column.
- Instance and column-level `toggleGroupBy` functions are also made available for programmatic grouping.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.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)
- `disableGroupBy: Bool`
- Disables groupBy for the entire table.
- `aggregations: Object<aggregationKey: aggregationFn>`
- Must be **memoized**
- Allows overriding or adding additional aggregation functions for use when grouping/aggregating row values. If an aggregation key isn't found on this object, it will default to using the built-in aggregation functions
- `groupByFn: Function`
- Must be **memoized**
- Defaults to `defaultGroupByFn`
- This function is responsible for grouping rows based on the `state.groupBy` keys provided. It's very rare you would need to customize this function.
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
- `Aggregated: Function | React.Component => JSX`
- Optional
- Defaults to this column's `Cell` formatter
- Receives the table instance and cell model as props
- Must return valid JSX
- This function (or component) formats this column's value when it is being grouped and aggregated, eg. If this column was showing the number of visits for a user to a website and it was currently being grouped to show an **average** of the values, the `Aggregated` function for this column could format that value to `1,000 Avg. Visits`
- `aggregate: String | [String, String] | Function(values, rows, isAggregated: Bool) => any`
- If a single `String` is passed, it must be the key of either a user defined or predefined `aggregations` function.
- If a tuple array of `[String, String]` is passed, both must be a key of either a user defined or predefined `aggregations` function.
- The first is used to aggregate raw values, eg. `sum`-ing raw values together
- The second is used to aggregate values that have already been aggregated, eg. `average`-ing the sums produced by the raw aggregation level
- If a `Function` is passed, this function will receive the `values`, original `rows` of those values, and an `isAggregated` `Bool` of whether or not the values and rows have already been aggregated.
- `disableGroupBy: Boolean`
- Defaults to `false`
- If `true`, will disable grouping for this column.
### Instance Properties
The following values are provided to the table `instance`:
- `rows: Array<Row>`
- An array of **grouped and aggregated** rows.
- `preGroupedRows: Array<Row>`
- The array of rows originally used to create the grouped rows.
- `toggleGroupBy: Function(columnId: String, ?set: Bool) => void`
- This function can be used to programmatically set or toggle the groupBy state for a specific column.
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `canGroupBy: Boolean`
- If `true`, this column is able to be grouped.
- This is resolved from the column having a valid accessor / data model, and not being manually disabled via other `useGroupBy` related options
- `isGrouped: Boolean`
- If `true`, this column is currently being grouped
- `groupedIndex: Int`
- If this column is currently being grouped, this integer is the index of this column's ID in the table state's `groupBy` array.
- `toggleGroupBy: Function(?set: Bool) => void`
- This function can be used to programmatically set or toggle the groupBy state fo this column.
- `getGroupByToggleProps: Function(props) => props`
- **Required**
- This function is used to resolve any props needed for this column's UI that is responsible for toggling grouping when the user clicks it.
- You can use the `getGroupByToggleProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props may override built-in sortBy props, so be careful!**
### Row Properties
The following properties are available on every `Row` object returned by the table instance.
- `groupById: String`
- The column ID for which this row is being grouped.
- Will be `undefined` if the row is an original row from `data` and not a materialized one from the grouping.
- `groupByVal: any`
- If the row is a materialized group row, this will be the grouping value that was used to create it.
- `values: Object`
- Similar to a regular row, a materialized grouping row also has a `values` object
- This object contains the **aggregated** values for this row's sub rows
- `subRows: Array<Row>`
- 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`.
- `isAggregated: Bool`
- Will be `true` if the row is an aggregated row
### Cell Properties
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
- `isGrouped: Bool`
- If `true`, this cell is a grouped cell, meaning it contains a grouping value and should usually display and expander.
- `isRepeatedValue: Bool`
- If `true`, this cell is a repeated value cell, meaning it contains a value that is already being displayed elsewhere (usually by a parent row's cell).
- Most of the time, this cell is not required to be displayed and can safely be hidden during rendering
- `isAggregated: Bool`
- If `true`, this cell's value has been aggregated and should probably be rendered with the `Aggregated` cell renderer.
### Example
- [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)
+88
View File
@@ -0,0 +1,88 @@
# `usePagination`
- Plugin Hook
- Optional
`usePagination` is the hook that implements **row pagination**. It can be used for both client-side pagination or server-side pagination. For more information on pagination, see Pagination
> **NOTE** Some server-side pagination implementations do not use page index and instead use **token based pagination**! If that's the case, please use the `useTokenPagination` plugin instead.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.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`
- **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)
- `autoResetPage: Boolean`
- Defaults to `true`
- When `true`, the `expanded` 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`
- Optional
- Only applies when using the `useExpanded` plugin hook simultaneously
- Defaults to `true`
- If set to `true`, expanded rows are paginated along with normal rows. This results in stable page sizes across every page.
- If set to `false`, expanded rows will be spliced in after pagination. This means that the total number of rows in a page can potentially be larger than the page size, depending on how many subrows are expanded.
### Instance Properties
The following values are provided to the table `instance`:
- `page: Array<row>`
- An array of rows for the **current** page, determined by the current `pageIndex` value.
- `pageCount: Int`
- If `manualPagination` is set to `false`, this is the total amount of pages available in the table based on the current `pageSize` value
- if `manualPagination` is set to `true`, this is merely the same `pageCount` option that was passed in the table options.
- `pageOptions: Array<Int>`
- An array of zero-based index integers corresponding to available pages in the table.
- This can be useful for generating things like select interfaces for the user to select a page from a list, instead of manually paginating to the desired page.
- `canPreviousPage: Bool`
- If there are pages and the current `pageIndex` is greater than `0`, this will be `true`
- `canNextPage:`
- If there are pages and the current `pageIndex` is less than `pageCount`, this will be `true`
- `gotoPage: Function(pageIndex)`
- This function, when called with a valid `pageIndex`, will set `pageIndex` to that value.
- If the aginateassed index is outside of the valid `pageIndex` range, then this function will do nothing.
- `previousPage: Function`
- This function decreases `state.pageIndex` by one.
- If there are no pages or `canPreviousPage` is false, this function will do nothing.
- `nextPage: Function`
- This function increases `state.pageIndex` by one.
- If there are no pages or `canNextPage` is false, this function will do nothing.
- `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
- Basic 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)
- Controlled 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)
+35
View File
@@ -0,0 +1,35 @@
# `useResizeColumns`
- Plugin Hook
- Optional
`useResizeColumns` is a plugin hook that adds support for resizing headers and cells when using non-table elements for layout eg. the `useBlockLayout` and `useAbsoluteLayout` hooks. It even supports resizing column groups!
### Table Options
- `disableResizing: Bool`
- Defaults to `false`
- When set to `true`, resizing is disabled across the entire table
### Column Options
The core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
- `disableResizing: Bool`
- Defaults to `false`
- When set to `true`, resizing is disabled for this column
### Header Properties
- `getResizerProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
- `canResize: Bool`
- Will be `true` if this column can be resized
- `isResizing: Bool`
- Will be `true` if this column is currently being resized
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-resizing)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
+65
View File
@@ -0,0 +1,65 @@
# `useRowSelect`
- Plugin Hook
- Optional
`useRowSelect` is the hook that implements **basic row selection**. For more information on row selection, see Row Selection
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.selectedRowPaths: Set<RowPathKey>`
- 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
- `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
- `autoResetSelectedRows: 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)
### Instance Properties
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`
- 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`
- Use this function to get the props needed for a **select all checkbox**.
- Props:
- `onChange: Function()`
- `style.cursor: 'pointer'`
- `checked: Bool`
- `title: 'Toggle All Rows Selected'`
- `isAllRowsSelected: Bool`
- Will be `true` if all rows are selected.
- If at least one row is not selected, will be `false`
- `selectedFlatRows: Array<Row>`
- The flat array of rows that are currently selected
### Row Properties
The following additional properties are available on every **prepared** `row` object returned by the table instance.
- `isSelected: Bool`
- Will be `true` if the row 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
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/row-selection)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-selection)
+61
View File
@@ -0,0 +1,61 @@
# `useRowState`
- Plugin Hook
- Optional
`useRowState` is a plugin hook that implements **basic state management for _prepared_ rows and their cells**.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.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.
- 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`
- `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)
### Instance Properties
The following values are provided to the table `instance`:
- `setRowState: Function(rowPath: Array<string>, updater: Function | Any) => void`
- Use this function to programmatically update the state of a row.
- `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.
- `setCellState: Function(rowPath: Array<string>, columnId: String, updater: Function | Any) => void`
- Use this function to programmatically update the cell of a row.
- `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.
### Row Properties
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('.')]`
- 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.
- `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.
### Cell Properties
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]`
- `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.
+127
View File
@@ -0,0 +1,127 @@
# `useSortBy`
- Plugin Hook
- Optional
`useSortBy` is the hook that implements **row sorting**. It also support multi-sort (keyboard required).
- Multi-sort is enabled by default
- To sort the table via UI, attach the props generated from each column's `getSortByToggleProps()`, then click any of those elements.
- To multi-sort the table via UI, hold `shift` while clicking on any of those same elements that have the props from `getSortByToggleProps()` attached.
- To programmatically sort (or multi-sort) any column, use the `toggleSortBy` method located on the instance or each individual column.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.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`
- 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.
- `defaultCanSort: Bool`
- Optional
- Defaults to `false`
- If set to `true`, all columns will be sortable, regardless if they have a valid `accessor`
- `disableMultiSort: Bool`
- Disables multi-sorting for the entire table.
- `isMultiSortEvent: Function`
- Allows to override default multisort behaviour(i.e. multisort applies when shift key is pressed), if this function is provided then returned boolean value from this function will make decision whether newly applied sort action will be considered as multisort or not.
- Receives `event` as argument.
- `maxMultiSortColCount: Number`
- Limit on max number of columns for multisort, e.g. if set to 3, and suppose table is sorted by `[A, B, C]` and then clicking `D` for sorting should result in table sorted by `[B, C , D]`
- `disableSortRemove: Bool`
- If true, the un-sorted state will not be available to columns once they have been sorted.
- `disableMultiRemove: Bool`
- If true, the un-sorted state will not be available to multi-sorted columns.
- `orderByFn: Function`
- Must be **memoized**
- Defaults to the built-in default orderBy function
- This function is responsible for composing multiple sorting functions together for multi-sorting, and also handles both the directional sorting and stable-sorting tie breaking. Rarely would you want to override this function unless you have a very advanced use-case that requires it.
- `sortTypes: Object<sortKey: sortType>`
- 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
- `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)
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
- `defaultCanSort: Bool`
- Optional
- Defaults to `false`
- If set to `true`, this column will be sortable, regardless if it has a valid `accessor`
- `disableSortBy: Bool`
- Optional
- Defaults to `false`
- If set to `true`, the sorting for this column will be disabled
- `sortDescFirst: Bool`
- Optional
- Defaults to `false`
- If set to `true`, the first sort direction for this column will be descending instead of ascending
- `sortInverted: Bool`
- Optional
- Defaults to `false`
- If set to `true`, the underlying sorting direction will be inverted, but the UI will not.
- This may be useful in situations where positive and negative connotation is inverted, eg. a Golfing score where a lower score is considered more positive than a higher one.
- `sortType: String | Function`
- Used to compare 2 rows of data and order them correctly.
- If a **function** is passed, it must be **memoized**
- String options: `basic`, `datetime`, `alphanumeric`. Defaults to `alphanumeric`.
- The resolved function from the this string/function will be used to sort the this column's data.
- If a `string` is passed, the function with that name located on either the custom `sortTypes` option or the built-in sorting types object will be used.
- If a `function` is passed, it will be used.
- For more information on sort types, see Sorting
### Instance Properties
The following values are provided to the table `instance`:
- `rows: Array<Row>`
- An array of **sorted** rows.
- `preSortedRows: Array<Row>`
- The array of rows that were originally sorted.
- `toggleSortBy: Function(ColumnId: String, descending: Bool, isMulti: Bool) => void`
- This function can be used to programmatically toggle the sorting for any specific column
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `canSort: Bool`
- Denotes whether a column is sortable or not depending on if it has a valid accessor/data model or is manually disabled via an option.
- `toggleSortBy: Function(descending, multi) => void`
- This function can be used to programmatically toggle the sorting for this column.
- This function is similar to the `instance`-level `toggleSortBy`, however, passing a columnId is not required since it is located on a `Column` object already.
- `getSortByToggleProps: Function(props) => props`
- **Required**
- This function is used to resolve any props needed for this column's UI that is responsible for toggling the sort direction when the user clicks it.
- You can use the `getSortByToggleProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props may override built-in sortBy props, so be careful!**
- `clearSorting: Function() => void`
- This function can be used to programmatically clear the sorting for this column.
- `isSorted: Boolean`
- Denotes whether this column is currently being sorted
- `sortedIndex: Int`
- If the column is currently sorted, this integer will be the index in the `sortBy` array from state that corresponds to this column.
- If this column is not sorted, the index will always be `-1`
- `isSortedDesc: Bool`
- If the column is currently sorted, this denotes whether the column's sort direction is descending or not.
- If `true`, the column is sorted `descending`
- If `false`, the column is sorted `ascending`
- If `undefined`, the column is not currently being sorted.
### Example
- [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)
+294
View File
@@ -0,0 +1,294 @@
# `useTable`
- Required
`useTable` is the root hook for React Table. To use it, pass it with an options object with at least a `columns` and `data` value, followed by any React Table compatible hooks you want to use.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `columns: Array<Column>`
- Required
- Must be **memoized**
- The core columns configuration object for the entire table.
- Supports nested `columns` arrays via the column's `columns` key, eg. `[{ Header: 'My Group', columns: [...] }]`
- `data: Array<any>`
- Required
- Must be **memoized**
- The data array that you want to display on the table.
- `initialState: Object`
- Optional
- The initial state object for the table.
- Upon table initialization, this object is **merged over the table's `defaultState` object** (eg. `{...defaultState, ...initialState}`) that React Table and its hooks use to register default state to produce the final initial state object passed to the `React.useState` hook internally.
- `initialState.hiddenColumns: Array<ColumnId: String>`
- Optional
- The initial state object for hidden columns
- If a column's ID is contained in this array, it will be hidden
- `reducer: Function(newState, action, prevState) => newState`
- Optional
- With every action that is dispatched to the table's internal `React.useReducer` instance, this reducer is called and is allowed to modify the final state object for updating.
- It is passed the `newState`, `action`, and `prevState` and is expected to either return the `newState` or a modified version of the `newState`
- May also be used to "control" the state of the table, by overriding certain pieces of state regardless of the action.
- `useControlledState: HookFunction(state) => controlledState`
- Optional
- If you need to control part of the table state, this is the place to do it.
- This function is run on every single render, just like a hook and allows you to alter the final state of the table if necessary.
- You can use hooks inside of this function, but most of the time, we just suggest using `React.useMemo` to memoize your state overrides.
- See the FAQ ["How can I manually control the table state?"](./faq.md#how-can-i-manually-control-the-table-state) for a an example.
- `defaultColumn: Object`
- Optional
- Defaults to `{}`
- The default column object for every column passed to React Table.
- Column-specific properties will override the properties in this object, eg. `{ ...defaultColumn, ...userColumn }`
- This is particularly useful for adding global column properties. For instance, when using the `useFilters` plugin hook, add a default `Filter` renderer for every column, eg.`{ Filter: MyDefaultFilterComponent }`
- `initialRowStateKey: String`
- Optional
- Defaults to `initialState`
- This key is used to look for the initial state of a row when initializing the `rowState` for a`data` array.
- If the value located at `row[initialRowStateKey]` is falsey, `{}` will be used instead.
- `getSubRows: Function(row, relativeIndex) => Rows[]`
- Optional
- Must be **memoized**
- 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.
- 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.
- `debug: Bool`
- Optional
- A flag to turn on debug mode.
- Defaults to `false`
### Column Options
The following options are supported on any column object you can pass to `columns`.
- `accessor: String | Function`
- **Required**
- This string/function is used to build the data model for your column.
- The data returned by an accessor should be **primitive** and sortable.
- If a string is passed, the column's value will be looked up on the original row via that key, eg. If your column's accessor is `firstName` then its value would be read from `row['firstName']`. You can also specify deeply nested values with accessors like `info.hobbies` or even `address[0].street`
- If a function is passed, the column's value will be looked up on the original row using this accessor function, eg. If your column's accessor is `row => row.firstName`, then its value would be determined by passing the row to this function and using the resulting value.
- `id: String`
- **Required if `accessor` is a function**
- This is the unique ID for the column. It is used by reference in things like sorting, grouping, filtering etc.
- If a **string** accessor is used, it defaults as the column ID, but can be overridden if necessary.
- `columns: Array<Column>`
- Optional
- A nested array of columns.
- If defined, the column will act as a header group. Columns can be recursively nested as much as needed.
- `Header: String | Function | React.Component => JSX`
- Optional
- Defaults to `() => null`
- Receives the table instance and column model as props
- Must either be a **string or return valid JSX**
- If a function/component is passed, it will be used for formatting the header value, eg. You can use a `Header` function to dynamically format the header using any table or column state.
- `Cell: Function | React.Component => JSX`
- Optional
- Defaults to `({ cell: { value } }) => String(value)`
- 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.
- `width: Int`
- Optional
- Defaults to `150`
- Specifies the width for the column (when using non-table-element layouts)
- `minWidth: Int`
- Optional
- Defaults to `0`
- Specifies the minimum width for the column (when using non-table-element layouts)
- Specifically useful when using plugin hooks that allow the user to resize column widths
- `maxWidth: Int`
- Optional
- Defaults to `0`
- Specifies the maximum width for the column (when using non-table-element layouts)
- Specifically useful when using plugin hooks that allow the user to resize column widths
### Instance Properties
The following properties are available on the table instance returned from `useTable`
- `state: Object`
- **Memoized** - This object reference will not change unless the internal table state is modified.
- This is the final state object of the table, which is the product of the `initialState`, internal table reducer and (optionally) a custom `reducer` supplied by the user.
- `dispatch: Function({ type: Actions[type], ...payload }) => void`
- This function is used both internally by React Table, and optionally by you (the developer) to update the table state programmatically.
- `type: Actions[type] | String`
- The action type corresponding to what action being taken against the state.
- `...payload`
- Any other action data that is associated with the action
- `columns: Array<Column>`
- A **nested** array of final column objects, **similar in structure to the original columns configuration option**.
- See [Column Properties](#column-properties) for more information
- `flatColumns: Array<Column>`
- A **flat** array of all final column objects.
- See [Column Properties](#column-properties) for more information
- `headerGroups: Array<HeaderGroup>`
- An array of normalized header groups, each containing a flattened array of final column objects for that row.
- **Some of these headers may be materialized as placeholders**
- See [HeaderGroup Properties](#headergroup-properties) for more information
- `footerGroups: Array<HeaderGroup>`
- An array of normalized header groups, but in reverse order, each containing a flattened array of final column objects for that row.
- **Some of these headers may be materialized as placeholders**
- See [HeaderGroup Properties](#headergroup-properties) for more information
- `headers: Array<Column>`
- A **nested** array of final header objects, **similar in structure to the original columns configuration option, but rebuilt for ordering**
- Each contains the headers that are displayed underneath it.
- **Some of these headers may be materialized as placeholders**
- See [Column Properties](#column-properties) for more information
- `flatHeaders[] Array<Column>`
- A **flat** array of final header objects found in each header group.
- **Some of these headers may be materialized as placeholders**
- See [Column Properties](#column-properties) for more information
- `rows: Array<Row>`
- An array of **materialized row objects** from the original `data` array and `columns` passed into the table options
- See [Row Properties](#row-properties) for more information
- `getTableProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for your table wrapper.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `getTableBodyProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for your table body wrapper.
- Custom props may be passed. **NOTE: Custom props will override built-in table body props, so be careful!**
- `prepareRow: Function(Row)`
- **Required**
- This function is responsible for lazily preparing a row for rendering. Any row that you intend to render in your table needs to be passed to this function **before every render**.
- **Why?** Since table data could potentially be very large, it can become very expensive to compute all of the necessary state for every row to be rendered regardless if it actually is rendered or not (for example if you are paginating or virtualizing the rows, you may only have a few rows visible at any given moment). This function allows only the rows you intend to display to be computed and prepped with the correct state.
- `flatRows: Array<Row>`
- An array of all rows, including subRows which have been flattened into the order in which they were detected (depth first)
- This can be helpful in calculating total row counts that must include subRows
- `totalColumnsWidth: Int`
- This is the total width of all visible columns (only available when using non-table-element layouts)
- `toggleHideColumn: Function(columnId: String, ?value: Boolean) => void`
- This function can be used to toggle or set a column's hidden state
- Passing a `value` is optional. If passed, the hidden state will be set to that Boolean value.
- If a `value` is not passed, the visibility for this column will be toggled.
- `setHiddenColumns: Function(Array<ColumnId: String> | Function(oldHiddenColumns) => Array<ColumnId: String>) => void`
- This function can be used to set the `hiddenColumns` state for the entire table.
- If a value is passed, `hiddenColumns` will be set to that value
- If a function is passed, it will received the previous `hiddenColumns` value and will be expected to return the new value.
- `toggleHideAllColumns: Function(?value: Boolean) => void`
- This function can be used to toggle or set the visibility for all columns to `true` or `false`
- If a value is not passed, the visibility for all columns will be toggled back and forth from `true` to `false`
- If `true` is passed, all columns will be hidden
- If a `false` is passed, all columns will be visible
- `getToggleHideAllColumnsProps: Function(userProps) => props`
- This function can be used to retrieve all necessary props to be placed on an `<input type='checkbox'>` component that will control the visibility of all columns
### HeaderGroup Properties
The following additional properties are available on every `headerGroup` object returned by the table instance.
- `headers: Array<Column>`
- **Required**
- The columns in this header group.
- `getHeaderGroupProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this header group's row.
- You can use the `getHeaderGroupProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `getFooterGroupProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this header group's footer row.
- You can use the `getFooterGroupProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `id: String`
- The resolved column ID from either the column's `accessor` or the column's hard-coded `id` property
- `isVisible: Boolean`
- Whether the column should be currently visible or not.
- Columns that are not visible are still used for sorting, filtering, etc.
- `render: Function(type: String | Function | Component, ?props)`
- This function is used to render content with the added context of a column.
- The entire table `instance` will be passed to the renderer with the addition of a `column` property, containing a reference to the column
- If `type` is a string, will render using the `column[type]` renderer. React Table ships with default `Header` and `Footer` renderers. Other renderers like `Filter` and `Aggregated` are available via plugin hooks.
- If a function or component is passed instead of a string, it will be be passed the table instance and column model as props and is expected to return any valid JSX.
- `totalLeft: Int`
- This is the total width in pixels of all columns to the left of this column
- Specifically useful when using plugin hooks that allow the user to resize column widths
- `totalWidth: Int`
- This is the total width in pixels for this column (if it is a leaf-column) or or all of it's sub-columns (if it is a column group)
- Specifically useful when using plugin hooks that allow the user to resize column widths
- `getHeaderProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this column's header cell.
- You can use the `getHeaderProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `getFooterProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this column's footer cell.
- You can use the `getFooterProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `toggleHidden: Function(?hidden: Boolean) => void`
- This function can be used to hide or show this column.
- If no value is passed, the visibility of this column will be toggled.
- Optionally pass a value to set the visible.
- `getToggleHiddenProps: Function(userProps) => props`
- This function can be used to retrieve all necessary props to be placed on an `<input type='checkbox'>` component that will control the visibility of this column.
### Row Properties
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.
- 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' }`
- `getRowProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this row.
- You can use the `getRowProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `index: Int`
- 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`
- The current state of the row. It's lifespan is attached to that of the original `data` array. When the raw `data` is changed, this state value is reset to the row's initial value (using the `initialRowStateKey` option).
- Can be updated via `instance.setRowState` or the row's `setState` function.
### Cell Properties
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
- `column: Column`
- The corresponding column object for this cell
- `row: Row`
- The corresponding row object for this cell
- `value: any`
- The **resolved** value for this cell.
- By default, this value is displayed on the table via the default `Cell` renderer. To override the way a cell displays
- `getCellProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this cell.
- You can use the `getCellProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `render: Function(type: String | Function | Component, ?props)`
- **Required**
- This function is used to render content with the added context of a cell.
- The entire table `instance` will be passed to the renderer with the addition of `column`, `row` and `cell` properties, containing a reference to each respective item.
- If `type` is a string, will render using the `column[type]` renderer. React Table ships with a default `Cell` renderer. Other renderers like `Aggregated` are available via hooks like `useFilters`.
- If a function or component is passed instead of a string, it will be be passed the table instance and cell model as props and is expected to return any valid JSX.
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/basic)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
+8
View File
@@ -0,0 +1,8 @@
# `useTokenPagination (Coming Soon)`
- Plugin Hook
- Optional
`useTokenPagination` is the hook that **aids in implementing row pagination using tokens**. It is useful for server-side pagination implementations that use **tokens** instead of page index. For more information on pagination, see Pagination
> Documentation Coming Soon...
+1 -1
View File
@@ -30,4 +30,4 @@ As of React Table v7, **you the developer** are responsible for rendering your o
After reading about React Table's concepts, you should:
- [Check Out Some Examples](./examples.md)
- [Study the API](./api.md)
- [Study the API](./api/README.md)
+6
View File
@@ -4,6 +4,9 @@
- Basic
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/basic)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
- Footers
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/footers)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/footers)
- Sorting
- [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)
@@ -31,6 +34,9 @@
- Column Ordering
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
- Column Hiding
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-hiding)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-hiding)
- Column Resizing
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-resizing)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
+94 -2
View File
@@ -20,10 +20,102 @@ useTable({
...state,
pageIndex: controlledPageIndex,
}),
[controlledPageIndex]
[state, controlledPageIndex]
)
},
})
```
**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 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 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 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, 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({
...
autoResetPage: !skipPageReset,
autoResetExpanded: !skipPageReset,
autoResetGroupBy: !skipPageReset,
autoResetSelectedRows: !skipPageReset,
autoResetSortBy: !skipPageReset,
autoResetFilters: !skipPageReset,
autoResetRowState: !skipPageReset,
})
```
Now, when we update our data, the above table states will not automatically reset!
+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-beta.28"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-beta.28.tgz#f5cd37b09fdbc7f22f472d021c56637d9fae097c"
integrity sha512-Ym05FAFNPGU6cid3Uw2W2+tn3mfGqKkLs51dw5FAJyz3fFNV0/i/CrTzHXZbVDA/KO2KNFYUjKGQJxIiDbXb4w==
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/column-hiding)
- `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>
@@ -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"
}
+158
View File
@@ -0,0 +1,158 @@
import React from 'react'
import styled from 'styled-components'
import { useTable } 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;
}
}
}
`
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 {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
flatColumns,
getToggleHideAllColumnsProps,
state,
} = useTable({
columns,
data,
})
// Render the UI for your table
return (
<>
<div>
<div>
<IndeterminateCheckbox {...getToggleHideAllColumnsProps()} /> Toggle
All
</div>
{flatColumns.map(column => (
<div key={column.id}>
<input type="checkbox" {...column.getToggleHiddenProps()} />{' '}
{column.id}
</div>
))}
<br />
</div>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</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>
)
})}
</tbody>
</table>
<pre>{JSON.stringify(state, null, 2)}</pre>
</>
)
}
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',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
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
+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;
@@ -1,6 +1,6 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, utils } 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
{...utils.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 {...utils.mergeProps(row.getRowProps(), getRowProps(row))}>
// Merge user row props in
<tr {...row.getRowProps(getRowProps(row))}>
{row.cells.map(cell => {
return (
<td
// Merge cell props
{...utils.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.
+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/footers)
- `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"
}
+169
View File
@@ -0,0 +1,169 @@
import React from 'react'
import styled from 'styled-components'
import { useTable } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
${'' /* :first-child {
td {
border-top: 1px solid black;
}
} */}
: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;
}
}
tfoot {
tr:first-child {
td {
border-top: 2px solid black;
}
}
font-weight: bolder;
}
}
`
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableBodyProps,
headerGroups,
footerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})
// Render the UI for your table
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(group => (
<tr {...group.getHeaderGroupProps()}>
{group.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</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>
)
})}
</tbody>
<tfoot>
{footerGroups.map(group => (
<tr {...group.getFooterGroupProps()}>
{group.headers.map(column => (
<td {...column.getFooterProps()}>{column.render('Footer')}</td>
))}
</tr>
))}
</tfoot>
</table>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
Footer: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
Footer: 'First Name',
},
{
Header: 'Last Name',
accessor: 'lastName',
Footer: 'Last Name',
},
],
},
{
Header: 'Info',
Footer: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
Footer: 'Age',
},
{
Header: 'Visits',
accessor: 'visits',
Footer: info => {
// Only calculate total visits if rows change
const total = React.useMemo(
() =>
info.rows.reduce((sum, row) => row.values.visits + sum, 0),
[info.rows]
)
return <>Total: {total}</>
},
},
{
Header: 'Status',
accessor: 'status',
Footer: 'Status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
Footer: 'Profile 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
+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"
+1 -1
View File
@@ -306,7 +306,7 @@ 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,
+3 -3
View File
@@ -303,9 +303,9 @@ 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,
+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"
+15 -21
View File
@@ -13,12 +13,7 @@ import makeData from './makeData'
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
rows,
prepareRow,
} = useTable({
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
columns,
data,
})
@@ -38,21 +33,20 @@ function Table({ columns, data }) {
))}
</TableHead>
<TableBody>
{rows.map(
(row, i) => {
prepareRow(row);
return (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<TableCell {...cell.getCellProps()}>
{cell.render('Cell')}
</TableCell>
)
})}
</TableRow>
)}
)}
{rows.map((row, i) => {
prepareRow(row)
return (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<TableCell {...cell.getCellProps()}>
{cell.render('Cell')}
</TableCell>
)
})}
</TableRow>
)
})}
</TableBody>
</MaUTable>
)
+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"
-1
View File
@@ -47,7 +47,6 @@ function Table({ columns, data }) {
{
columns,
data,
debug: true,
},
useRowSelect
)
+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"
+1 -1
View File
@@ -65,7 +65,7 @@ By default, the sorting will be `alphanumeric`. This can be changed in your `col
Other options include `basic` and `datetime`.
Note that if you're planning on sorting numbers between 0 and 1, `basic` sorting will be more accurate.
More information can be found in the [API Docs](/docs/api.md#useSortBy)
More information can be found in the [API Docs](/docs/api/README.md#useSortBy)
````diff
const columns = React.useMemo(
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "react-table",
"version": "7.0.0-beta.27",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"version": "7.0.0-rc.7",
"description": "Hooks for building lightweight, fast and extendable datagrids for React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
"repository": {
+120
View File
@@ -1,4 +1,124 @@
[
{
"timestamp": 1576003432935,
"files": [
{
"filename": "index.js",
"size": 22620,
"delta": 652
}
]
},
{
"timestamp": 1575985310396,
"files": [
{
"filename": "index.js",
"size": 21968,
"delta": 323
}
]
},
{
"timestamp": 1575910923566,
"files": [
{
"filename": "index.js",
"size": 21645,
"delta": 56
}
]
},
{
"timestamp": 1575859193604,
"files": [
{
"filename": "index.js",
"size": 21589,
"delta": 563
}
]
},
{
"timestamp": 1575690248030,
"files": [
{
"filename": "index.js",
"size": 21026,
"delta": 1
}
]
},
{
"timestamp": 1575675308812,
"files": [
{
"filename": "index.js",
"size": 21025,
"delta": -421
}
]
},
{
"timestamp": 1575620433902,
"files": [
{
"filename": "index.js",
"size": 21446,
"delta": -1
}
]
},
{
"timestamp": 1575607054721,
"files": [
{
"filename": "index.js",
"size": 21447,
"delta": 26
}
]
},
{
"timestamp": 1575605755429,
"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": [
+110
View File
@@ -1,4 +1,114 @@
[
{
"timestamp": 1576003439933,
"files": [
{
"filename": "index.es.js",
"size": 22438,
"delta": 656
}
]
},
{
"timestamp": 1575985317929,
"files": [
{
"filename": "index.es.js",
"size": 21782,
"delta": 324
}
]
},
{
"timestamp": 1575910931774,
"files": [
{
"filename": "index.es.js",
"size": 21458,
"delta": 55
}
]
},
{
"timestamp": 1575859200604,
"files": [
{
"filename": "index.es.js",
"size": 21403,
"delta": 561
}
]
},
{
"timestamp": 1575675317538,
"files": [
{
"filename": "index.es.js",
"size": 20842,
"delta": -383
}
]
},
{
"timestamp": 1575620442742,
"files": [
{
"filename": "index.es.js",
"size": 21225,
"delta": -1
}
]
},
{
"timestamp": 1575607059725,
"files": [
{
"filename": "index.es.js",
"size": 21226,
"delta": 26
}
]
},
{
"timestamp": 1575605764195,
"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": [
+214
View File
@@ -0,0 +1,214 @@
import React from 'react'
import {
actions,
functionalUpdate,
useGetLatest,
useConsumeHookGetter,
makePropGetter,
} from '../utils'
actions.resetHiddenColumns = 'resetHiddenColumns'
actions.toggleHideColumn = 'toggleHideColumn'
actions.setHiddenColumns = 'setHiddenColumns'
actions.toggleHideAllColumns = 'toggleHideAllColumns'
export const useColumnVisibility = hooks => {
hooks.getToggleHiddenProps = [defualtGetToggleHiddenProps]
hooks.getToggleHideAllColumnsProps = [defualtGetToggleHideAllColumnsProps]
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 defualtGetToggleHiddenProps = (props, instance, column) => [
props,
{
onChange: e => {
column.toggleHidden(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: column.isVisible,
title: 'Toggle Column Visible',
},
]
const defualtGetToggleHideAllColumnsProps = (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, instanceRef) {
if (action.type === actions.init) {
return {
hiddenColumns: [],
...state,
}
}
if (action.type === actions.resetHiddenColumns) {
return {
...state,
hiddenColumns: [],
}
}
if (action.type === actions.toggleHideColumn) {
const should =
typeof action.value !== 'undefined'
? action.value
: !state.hiddenColumns.includes(action.columnId)
const hiddenColumns = should
? [...state.hiddenColumns, action.columnId]
: state.hiddenColumns.filter(d => d !== action.columnId)
return {
...state,
hiddenColumns,
}
}
if (action.type === actions.setHiddenColumns) {
return {
...state,
hiddenColumns: functionalUpdate(action.value, state.hiddenColumns),
}
}
if (action.type === actions.toggleHideAllColumns) {
const shouldAll =
typeof action.value !== 'undefined'
? action.value
: !state.hiddenColumns.length
return {
...state,
hiddenColumns: shouldAll
? instanceRef.current.flatColumns.map(d => d.id)
: [],
}
}
}
function useInstanceBeforeDimensions(instance) {
const {
headers,
state: { hiddenColumns },
} = instance
const handleColumn = (column, parentVisible) => {
column.isVisible = parentVisible && !hiddenColumns.includes(column.id)
let totalVisibleHeaderCount = 0
if (column.headers && column.headers.length) {
column.headers.forEach(
subColumn =>
(totalVisibleHeaderCount += handleColumn(subColumn, column.isVisible))
)
} else {
totalVisibleHeaderCount = column.isVisible ? 1 : 0
}
column.totalVisibleHeaderCount = totalVisibleHeaderCount
return totalVisibleHeaderCount
}
let totalVisibleHeaderCount = 0
headers.forEach(
subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
)
}
function useInstance(instance) {
const {
flatHeaders,
dispatch,
flatColumns,
state: { hiddenColumns },
} = instance
const getInstance = useGetLatest(instance)
const allColumnsHidden = flatColumns.length === hiddenColumns.length
const toggleHideColumn = React.useCallback(
(columnId, value) =>
dispatch({ type: actions.toggleHideColumn, columnId, value }),
[dispatch]
)
const setHiddenColumns = React.useCallback(
value => dispatch({ type: actions.setHiddenColumns, value }),
[dispatch]
)
const toggleHideAllColumns = React.useCallback(
value => dispatch({ type: actions.toggleHideAllColumns, value }),
[dispatch]
)
// Snapshot hook and disallow more from being added
const getToggleHideAllColumnsPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleHideAllColumnsProps'
)
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,
})
}
+374 -260
View File
@@ -2,23 +2,23 @@ import React from 'react'
//
import {
applyHooks,
applyPropHooks,
mergeProps,
actions,
reduceHooks,
loopHooks,
makePropGetter,
flexRender,
decorateColumnTree,
makeHeaderGroups,
flattenBy,
determineHeaderVisibility,
useGetLatest,
useConsumeHookGetter,
} from '../utils'
const 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.'
import makeDefaultPluginHooks from '../makeDefaultPluginHooks'
export const actions = {
init: 'init',
}
export const reducerHandlers = {}
import { useColumnVisibility } from './useColumnVisibility'
let renderErr = 'Renderer Error'
const defaultInitialState = {}
const defaultColumnInstance = {}
@@ -27,143 +27,223 @@ const defaultGetSubRows = (row, index) => row.subRows || []
const defaultGetRowId = (row, index) => 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
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.log('')
console.log('React Table Action: ', action)
console.log('New State: ', nextState)
}
return nextState
return {
...rest,
initialState,
defaultColumn,
getSubRows,
getRowId,
stateReducer,
useControlledState,
}
}
// But use the users table state if provided
const [reducerState, originalDispatch] = React.useReducer(
reducer,
undefined,
() => reducer(initialState, { type: actions.init })
)
export const useTable = (props, ...plugins) => {
// Apply default props
props = applyDefaults(props)
const state = useControlledState(reducerState)
// Add core plugins
plugins = [useColumnVisibility, ...plugins]
// 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: [],
getHeaderProps: [],
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, instanceRef) || s,
state
)
},
[getStateReducers, getStateReducer]
)
// 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]
() =>
reduceHooks(
getColumnsHooks(),
decorateColumnTree(userColumns, defaultColumn),
getInstance()
),
[
defaultColumn,
getColumnsHooks,
getInstance,
userColumns,
// eslint-disable-next-line react-hooks/exhaustive-deps
...getColumnsDepsHooks(getInstance()),
]
)
getInstance().columns = columns
// Snapshot hook and disallow more from being added
const getFlatColumns = useConsumeHookGetter(
getInstance().hooks,
'flatColumns'
)
// Snapshot hook and disallow more from being added
const getFlatColumnsDeps = useConsumeHookGetter(
getInstance().hooks,
'flatColumnsDeps'
)
// 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 flatColumns = React.useMemo(
() =>
reduceHooks(
getFlatColumns(),
flattenBy(columns, 'columns'),
getInstance()
),
[
columns,
getFlatColumns,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
getFlatColumnsDeps(getInstance()),
]
)
let newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
flattenBy(columns, 'columns'),
instanceRef.current
)
getInstance().flatColumns = flatColumns
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.columnsBeforeHeaderGroups')
return newColumns
}, [
columns,
debug,
// eslint-disable-next-line react-hooks/exhaustive-deps
...applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
[],
instanceRef.current
),
])
// 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(
() => makeHeaderGroups(flatColumns, defaultColumn),
[defaultColumn, flatColumns]
() =>
reduceHooks(
getHeaderGroups(),
makeHeaderGroups(flatColumns, defaultColumn),
getInstance()
),
[
defaultColumn,
flatColumns,
getHeaderGroups,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
...getHeaderGroupsDeps(getInstance()),
]
)
const headers = React.useMemo(() => headerGroups[0].headers, [headerGroups])
getInstance().headerGroups = headerGroups
Object.assign(instanceRef.current, {
columns,
flatColumns,
headerGroups,
headers,
})
const headers = React.useMemo(
() => (headerGroups.length ? headerGroups[0].headers : []),
[headerGroups]
)
getInstance().headers = headers
// 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
@@ -218,46 +298,53 @@ 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])
}, [data, flatColumns, getRowId, getSubRows])
instanceRef.current.rows = rows
instanceRef.current.flatRows = flatRows
// Determine column visibility
determineHeaderVisibility(instanceRef.current)
getInstance().rows = rows
getInstance().flatRows = flatRows
// 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')
calculateDimensions(instanceRef.current)
loopHooks(getUseInstanceBeforeDimensions(), getInstance())
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useInstance')
instanceRef.current = applyHooks(
instanceRef.current.hooks.useInstance,
instanceRef.current
// Header Visibility is needed by this point
getInstance().totalColumnsWidth = calculateHeaderWidths(headers)
// 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 => {
getInstance().flatHeaders.forEach(column => {
// Give columns/headers rendering power
column.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
@@ -267,164 +354,191 @@ export const useTable = (props, ...plugins) => {
}
return flexRender(Comp, {
...instanceRef.current,
...getInstance(),
column,
...userProps,
})
}
// 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
)
column.getHeaderProps = makePropGetter(
getHeaderPropsHooks(),
getInstance(),
column
)
// Give columns/headers a default getFooterProps
column.getFooterProps = makePropGetter(
getFooterPropsHooks(),
getInstance(),
column
)
})
instanceRef.current.headerGroups.forEach((headerGroup, i) => {
// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers = headerGroup.headers.filter(header => {
const recurse = headers =>
headers.filter(header => {
if (header.headers) {
return recurse(header.headers)
}
return header.isVisible
}).length
if (header.headers) {
return recurse(header.headers)
}
return header.isVisible
})
// Snapshot hook and disallow more from being added
const getHeaderGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getHeaderGroupProps'
)
// Give headerGroups getRowProps
if (headerGroup.headers.length) {
headerGroup.getHeaderGroupProps = (props = {}) =>
mergeProps(
{
key: [`header${i}`].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getHeaderGroupProps,
headerGroup,
instanceRef.current
),
props
// Snapshot hook and disallow more from being added
const getFooterGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getFooterGroupProps'
)
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 => {
const recurse = headers =>
headers.filter(column => {
if (column.headers) {
return recurse(column.headers)
}
return column.isVisible
}).length
if (column.headers) {
return recurse(column.headers)
}
return column.isVisible
})
// Give headerGroups getRowProps
if (headerGroup.headers.length) {
headerGroup.getHeaderGroupProps = makePropGetter(
getHeaderGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
return true
headerGroup.getFooterGroupProps = makePropGetter(
getFooterGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
return true
}
return false
}
})
)
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 => {
const cell = {
column,
row,
value: row.values[column.id],
}
// Snapshot hook and disallow more from being added
const getRowPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getRowProps'
)
// 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
)
}
// Snapshot hook and disallow more from being added
const getCellPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getCellProps'
)
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
getInstance().prepareRow = React.useCallback(
row => {
row.getRowProps = makePropGetter(getRowPropsHooks(), getInstance(), row)
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
// Build the visible cells for each row
row.cells = getInstance()
.flatColumns.filter(d => d.isVisible)
.map(column => {
const cell = {
column,
row,
cell,
...userProps,
})
}
value: row.values[column.id],
}
return cell
})
// Give each cell a getCellProps base
cell.getCellProps = makePropGetter(
getCellPropsHooks(),
getInstance(),
cell
)
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
}, [])
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
instanceRef.current.getTableProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableProps,
instanceRef.current
),
userProps
)
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
instanceRef.current.getTableBodyProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableBodyProps,
instanceRef.current
),
userProps
)
return flexRender(Comp, {
...getInstance(),
column,
row,
cell,
...userProps,
})
}
return instanceRef.current
}
return cell
})
function calculateDimensions(instance) {
const { headers } = instance
// need to apply any row specific hooks (useExpanded requires this)
loopHooks(getPrepareRowHooks(), row, getInstance())
},
[getCellPropsHooks, getInstance, getPrepareRowHooks, getRowPropsHooks]
)
instance.totalColumnsWidth = calculateHeaderWidths(headers)
// Snapshot hook and disallow more from being added
const getTablePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getTableProps'
)
getInstance().getTableProps = makePropGetter(
getTablePropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getTableBodyPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getTableBodyProps'
)
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) {
+2 -4
View File
@@ -1,7 +1,5 @@
import * as utils from './utils'
export { utils }
export { defaultColumn } from './utils'
export { useTable, actions, reducerHandlers } from './hooks/useTable'
export * from './publicUtils'
export { useTable } from './hooks/useTable'
export { useExpanded } from './plugin-hooks/useExpanded'
export { useFilters } from './plugin-hooks/useFilters'
export { useGroupBy } from './plugin-hooks/useGroupBy'
+57
View File
@@ -0,0 +1,57 @@
const defaultGetHeaderProps = (props, instance, column) => ({
key: ['header', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
...props,
})
const defaultGetFooterProps = (props, instance, column) => ({
key: ['footer', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
...props,
})
const defaultGetHeaderGroupProps = (props, instance, headerGroup, index) => ({
key: ['header', index].join('_'),
...props,
})
const defaultGetFooterGroupProps = (props, instance, headerGroup, index) => ({
key: ['footer', index].join('_'),
...props,
})
const defaultGetRowProps = (props, instance, row) => ({
key: ['row', ...row.path].join('_'),
...props,
})
const defaultGetCellProps = (props, instance, cell) => ({
...props,
key: ['cell', ...cell.row.path, cell.column.id].join('_'),
})
export default function makeDefaultPluginHooks() {
return {
useOptions: [],
stateReducers: [],
columns: [],
columnsDeps: [],
flatColumns: [],
flatColumnsDeps: [],
headerGroups: [],
headerGroupsDeps: [],
useInstanceBeforeDimensions: [],
useInstance: [],
useRows: [],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getHeaderGroupProps: [defaultGetHeaderGroupProps],
getFooterGroupProps: [defaultGetFooterGroupProps],
getHeaderProps: [defaultGetHeaderProps],
getFooterProps: [defaultGetFooterProps],
getRowProps: [defaultGetRowProps],
getCellProps: [defaultGetCellProps],
useFinalInstance: [],
}
}
@@ -5,7 +5,7 @@ Snapshot Diff:
- First value
+ Second value
@@ -22,11 +22,13 @@
@@ -20,11 +20,13 @@
colspan="1"
style="cursor: pointer;"
title="Toggle SortBy"
@@ -20,7 +20,7 @@ Snapshot Diff:
colspan="1"
style="cursor: pointer;"
title="Toggle SortBy"
@@ -69,66 +71,66 @@
@@ -67,66 +69,66 @@
</tr>
</thead>
<tbody>
@@ -112,7 +112,7 @@ Snapshot Diff:
- First value
+ Second value
@@ -23,11 +23,11 @@
@@ -21,11 +21,11 @@
style="cursor: pointer;"
title="Toggle SortBy"
>
@@ -125,7 +125,7 @@ Snapshot Diff:
<th
colspan="1"
style="cursor: pointer;"
@@ -71,26 +71,26 @@
@@ -69,26 +69,26 @@
</tr>
</thead>
<tbody>
@@ -158,7 +158,7 @@ Snapshot Diff:
<tr>
<td>
firstName: joe
@@ -111,26 +111,26 @@
@@ -109,26 +109,26 @@
progress: 10
</td>
</tr>
+30 -42
View File
@@ -1,57 +1,45 @@
export const useAbsoluteLayout = hooks => {
hooks.useInstance.push(useInstance)
// Calculating column/cells widths
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)
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`,
},
},
]
+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'
+15 -23
View File
@@ -1,16 +1,23 @@
import React from 'react'
import { actions, reducerHandlers } from '../hooks/useTable'
import { functionalUpdate } from '../utils'
const pluginName = 'useColumnOrder'
import { functionalUpdate, actions } from '../utils'
// Actions
actions.resetColumnOrder = 'resetColumnOrder'
actions.setColumnOrder = 'setColumnOrder'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useColumnOrder = hooks => {
hooks.stateReducers.push(reducer)
hooks.flatColumnsDeps.push((deps, instance) => {
return [...deps, instance.state.columnOrder]
})
hooks.flatColumns.push(flatColumns)
hooks.useInstance.push(useInstance)
}
useColumnOrder.pluginName = 'useColumnOrder'
function reducer(state, action) {
if (action.type === actions.init) {
return {
columnOrder: [],
@@ -33,17 +40,7 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useColumnOrder = hooks => {
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
return [...deps, instance.state.columnOrder]
})
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.useInstance.push(useInstance)
}
useColumnOrder.pluginName = pluginName
function columnsBeforeHeaderGroups(columns, instance) {
function flatColumns(columns, instance) {
const {
state: { columnOrder },
} = instance
@@ -77,15 +74,10 @@ function columnsBeforeHeaderGroups(columns, instance) {
function useInstance(instance) {
const { dispatch } = instance
const setColumnOrder = React.useCallback(
instance.setColumnOrder = React.useCallback(
columnOrder => {
return dispatch({ type: actions.setColumnOrder, columnOrder })
},
[dispatch]
)
return {
...instance,
setColumnOrder,
}
}
+55 -66
View File
@@ -1,21 +1,42 @@
import React from 'react'
import {
mergeProps,
applyPropHooks,
actions,
makePropGetter,
expandRows,
safeUseLayoutEffect,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
import { actions, reducerHandlers } from '../hooks/useTable'
const pluginName = 'useExpanded'
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.toggleExpandedByPath = 'toggleExpandedByPath'
actions.resetExpanded = 'resetExpanded'
export const useExpanded = hooks => {
hooks.getExpandedToggleProps = [defaultGetExpandedToggleProps]
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useExpanded.pluginName = 'useExpanded'
const defaultGetExpandedToggleProps = (props, instance, row) => [
props,
{
onClick: e => {
e.persist()
row.toggleExpanded()
},
style: {
cursor: 'pointer',
},
title: 'Toggle Expanded',
},
]
// Reducer
reducerHandlers[pluginName] = (state, action) => {
function reducer(state, action) {
if (action.type === actions.init) {
return {
expanded: [],
@@ -34,7 +55,7 @@ reducerHandlers[pluginName] = (state, action) => {
const { path, expanded } = action
const key = path.join('.')
const exists = state.expanded.includes(key)
const shouldExist = typeof set !== 'undefined' ? expanded : !exists
const shouldExist = typeof expanded !== 'undefined' ? expanded : !exists
let newExpanded = new Set(state.expanded)
if (!exists && shouldExist) {
@@ -52,99 +73,67 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useExpanded = hooks => {
hooks.getExpandedToggleProps = []
hooks.useInstance.push(useInstance)
}
useExpanded.pluginName = pluginName
const defaultGetResetExpandedDeps = ({ data }) => [data]
function useInstance(instance) {
const {
debug,
data,
rows,
manualExpandedKey = 'expanded',
paginateExpandedRows = true,
expandSubRows = true,
hooks,
autoResetExpanded = true,
state: { expanded },
dispatch,
getResetExpandedDeps = defaultGetResetExpandedDeps,
} = instance
const getAutoResetExpanded = useGetLatest(autoResetExpanded)
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
useMountedLayoutEffect(() => {
if (getAutoResetExpanded()) {
dispatch({ type: actions.resetExpanded })
}
isMountedRef.current = true
}, [
dispatch,
...(getResetExpandedDeps ? getResetExpandedDeps(instance) : []),
])
}, [dispatch, data])
const toggleExpandedByPath = (path, expanded) => {
dispatch({ type: actions.toggleExpandedByPath, path, expanded })
}
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const getExpandedTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getExpandedToggleProps'
)
hooks.prepareRow.push(row => {
row.toggleExpanded = set => toggleExpandedByPath(row.path, set)
row.getExpandedToggleProps = props => {
return mergeProps(
{
onClick: e => {
e.persist()
row.toggleExpanded()
},
style: {
cursor: 'pointer',
},
title: 'Toggle Expanded',
},
applyPropHooks(
instanceRef.current.hooks.getExpandedToggleProps,
row,
instanceRef.current
),
props
)
}
return row
row.toggleExpanded = set => instance.toggleExpandedByPath(row.path, set)
row.getExpandedToggleProps = makePropGetter(
getExpandedTogglePropsHooks(),
getInstance(),
row
)
})
const expandedRows = React.useMemo(() => {
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getExpandedRows')
if (paginateExpandedRows) {
return expandRows(rows, { manualExpandedKey, expanded, expandSubRows })
}
return rows
}, [
debug,
paginateExpandedRows,
rows,
manualExpandedKey,
expanded,
expandSubRows,
])
}, [paginateExpandedRows, rows, manualExpandedKey, expanded, expandSubRows])
const expandedDepth = findExpandedDepth(expanded)
return {
...instance,
Object.assign(instance, {
toggleExpandedByPath,
expandedDepth,
preExpandedRows: rows,
expandedRows,
rows: expandedRows,
}
expandedDepth,
})
}
function findExpandedDepth(expanded) {
+32 -58
View File
@@ -1,23 +1,28 @@
import React from 'react'
import {
actions,
getFirstDefined,
isFunction,
safeUseLayoutEffect,
useMountedLayoutEffect,
functionalUpdate,
useGetLatest,
} from '../utils'
import * as filterTypes from '../filterTypes'
import { actions, reducerHandlers } from '../hooks/useTable'
const pluginName = 'useFilters'
// Actions
actions.resetFilters = 'resetFilters'
actions.setFilter = 'setFilter'
actions.setAllFilters = 'setAllFilters'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useFilters = hooks => {
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useFilters.pluginName = 'useFilters'
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
filters: {},
@@ -33,14 +38,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.setFilter) {
const {
columnId,
filterValue,
instanceRef: {
current: { flatColumns, userFilterTypes },
},
} = action
const { columnId, filterValue } = action
const { flatColumns, userFilterTypes } = instanceRef.current
const column = flatColumns.find(d => d.id === columnId)
if (!column) {
@@ -77,13 +76,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.setAllFilters) {
const {
filters,
instanceRef: {
current: { flatColumns, filterTypes: userFilterTypes },
},
} = action
const { filters } = action
const { flatColumns, filterTypes: userFilterTypes } = instanceRef.current
const newFilters = functionalUpdate(filters, state.filters)
// Filter out undefined values
@@ -108,15 +102,9 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useFilters = hooks => {
hooks.useInstance.push(useInstance)
}
useFilters.pluginName = pluginName
function useInstance(instance) {
const {
debug,
data,
rows,
flatRows,
flatColumns,
@@ -126,21 +114,9 @@ function useInstance(instance) {
disableFilters,
state: { filters },
dispatch,
getResetFiltersDeps = false,
autoResetFilters = true,
} = instance
const preFilteredRows = rows
const preFilteredFlatRows = flatRows
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
dispatch({ type: actions.resetFilters })
}
isMountedRef.current = true
}, [dispatch, ...(getResetFiltersDeps ? getResetFiltersDeps(instance) : [])])
const setFilter = (columnId, filterValue) => {
dispatch({ type: actions.setFilter, columnId, filterValue })
}
@@ -192,9 +168,6 @@ function useInstance(instance) {
const filteredFlatRows = []
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getFilteredRows')
// Filters top level and nested rows
const filterRows = (rows, depth = 0) => {
let filteredRows = rows
@@ -264,15 +237,7 @@ function useInstance(instance) {
filteredRows: filterRows(rows),
filteredFlatRows,
}
}, [
manualFilters,
filters,
debug,
rows,
flatRows,
flatColumns,
userFilterTypes,
])
}, [manualFilters, filters, rows, flatRows, flatColumns, userFilterTypes])
React.useMemo(() => {
// Now that each filtered column has it's partially filtered rows,
@@ -289,15 +254,24 @@ function useInstance(instance) {
})
}, [filteredRows, filters, flatColumns])
return {
...instance,
const getAutoResetFilters = useGetLatest(autoResetFilters)
useMountedLayoutEffect(() => {
if (getAutoResetFilters()) {
dispatch({ type: actions.resetFilters })
}
}, [dispatch, manualFilters ? null : data])
Object.assign(instance, {
setFilter,
setAllFilters,
preFilteredRows,
preFilteredFlatRows,
preFilteredRows: rows,
preFilteredFlatRows: flatRows,
filteredRows,
filteredFlatRows,
rows: filteredRows,
flatRows: filteredFlatRows,
}
})
}
function shouldAutoRemove(autoRemove, value) {
+62 -55
View File
@@ -1,23 +1,52 @@
import React from 'react'
import * as aggregations from '../aggregations'
import { actions, reducerHandlers } from '../hooks/useTable'
import {
mergeProps,
applyPropHooks,
actions,
makePropGetter,
defaultGroupByFn,
getFirstDefined,
ensurePluginOrder,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
const pluginName = 'useGroupBy'
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.resetGroupBy = 'resetGroupBy'
actions.toggleGroupBy = 'toggleGroupBy'
export const useGroupBy = hooks => {
hooks.getGroupByToggleProps = [defaultGetGroupByToggleProps]
hooks.stateReducers.push(reducer)
hooks.flatColumnsDeps.push((deps, instance) => [
...deps,
instance.state.groupBy,
])
hooks.flatColumns.push(flatColumns)
hooks.useInstance.push(useInstance)
}
useGroupBy.pluginName = 'useGroupBy'
const defaultGetGroupByToggleProps = (props, instance, header) => [
props,
{
onClick: header.canGroupBy
? e => {
e.persist()
header.toggleGroupBy()
}
: undefined,
style: {
cursor: header.canGroupBy ? 'pointer' : undefined,
},
title: 'Toggle GroupBy',
},
]
// Reducer
reducerHandlers[pluginName] = (state, action) => {
function reducer(state, action) {
if (action.type === actions.init) {
return {
groupBy: [],
@@ -52,18 +81,7 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useGroupBy = hooks => {
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
deps.push(instance.state.groupBy)
return deps
})
hooks.useInstance.push(useInstance)
}
useGroupBy.pluginName = pluginName
function columnsBeforeHeaderGroups(flatColumns, { state: { groupBy } }) {
function flatColumns(flatColumns, { state: { groupBy } }) {
// Sort grouped columns to the start of the column list
// before the headers are built
@@ -85,7 +103,7 @@ const defaultUserAggregations = {}
function useInstance(instance) {
const {
debug,
data,
rows,
flatRows,
flatColumns,
@@ -99,10 +117,14 @@ function useInstance(instance) {
plugins,
state: { groupBy },
dispatch,
autoResetGroupBy = true,
manaulGroupBy,
} = instance
ensurePluginOrder(plugins, [], 'useGroupBy', ['useSortBy', 'useExpanded'])
const getInstance = useGetLatest(instance)
flatColumns.forEach(column => {
const {
id,
@@ -132,36 +154,17 @@ function useInstance(instance) {
dispatch({ type: actions.toggleGroupBy, columnId, toggle })
}
hooks.getGroupByToggleProps = []
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getGroupByTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getGroupByToggleProps'
)
flatHeaders.forEach(header => {
const { canGroupBy } = header
header.getGroupByToggleProps = props => {
return mergeProps(
{
onClick: canGroupBy
? e => {
e.persist()
header.toggleGroupBy()
}
: undefined,
style: {
cursor: canGroupBy ? 'pointer' : undefined,
},
title: 'Toggle GroupBy',
},
applyPropHooks(
instanceRef.current.hooks.getGroupByToggleProps,
header,
instanceRef.current
),
props
)
}
header.getGroupByToggleProps = makePropGetter(
getGroupByTogglePropsHooks(),
getInstance(),
header
)
})
hooks.prepareRow.push(row => {
@@ -174,7 +177,6 @@ function useInstance(instance) {
cell.isAggregated =
!cell.isGrouped && !cell.isRepeatedValue && row.canExpand
})
return row
})
const [groupedRows, groupedFlatRows] = React.useMemo(() => {
@@ -182,10 +184,7 @@ function useInstance(instance) {
return [rows, flatRows]
}
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getGroupedRows')
// Find the columns that can or are aggregating
// Uses each column to aggregate rows into a single value
const aggregateRowsToValues = (rows, isAggregated) => {
const values = {}
@@ -288,7 +287,6 @@ function useInstance(instance) {
}, [
manualGroupBy,
groupBy,
debug,
rows,
flatRows,
flatColumns,
@@ -296,11 +294,20 @@ function useInstance(instance) {
groupByFn,
])
return {
...instance,
const getAutoResetGroupBy = useGetLatest(autoResetGroupBy)
useMountedLayoutEffect(() => {
if (getAutoResetGroupBy()) {
dispatch({ type: actions.resetGroupBy })
}
}, [dispatch, manaulGroupBy ? null : data])
Object.assign(instance, {
groupedRows,
groupedFlatRows,
toggleGroupBy,
rows: groupedRows,
flatRows: groupedFlatRows,
preGroupedRows: rows,
}
})
}
+32 -36
View File
@@ -2,12 +2,13 @@ import React from 'react'
//
import { actions, reducerHandlers } from '../hooks/useTable'
import {
actions,
ensurePluginOrder,
safeUseLayoutEffect,
expandRows,
functionalUpdate,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
const pluginName = 'usePagination'
@@ -17,8 +18,14 @@ actions.resetPage = 'resetPage'
actions.gotoPage = 'gotoPage'
actions.setPageSize = 'setPageSize'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const usePagination = hooks => {
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
usePagination.pluginName = pluginName
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
pageSize: 10,
@@ -35,7 +42,7 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.gotoPage) {
const { pageCount } = action.instanceRef.current
const { pageCount } = instanceRef.current
const newPageIndex = functionalUpdate(action.pageIndex, state.pageIndex)
if (newPageIndex < 0 || newPageIndex > pageCount - 1) {
@@ -60,31 +67,22 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const usePagination = hooks => {
hooks.useInstance.push(useInstance)
}
usePagination.pluginName = pluginName
const defaultGetResetPageDeps = ({
data,
manualPagination,
state: { filters, groupBy, sortBy },
}) => [manualPagination ? null : data, filters, groupBy, sortBy]
function useInstance(instance) {
const {
rows,
manualPagination,
getResetPageDeps = defaultGetResetPageDeps,
autoResetPage = true,
manualExpandedKey = 'expanded',
debug,
plugins,
pageCount: userPageCount,
paginateExpandedRows = true,
expandSubRows = true,
state: { pageSize, pageIndex, expanded },
state: { pageSize, pageIndex, expanded, filters, groupBy, sortBy },
dispatch,
data,
manualPagination,
manualFilters,
manualGroupBy,
manualSortBy,
} = instance
ensurePluginOrder(
@@ -94,14 +92,19 @@ function useInstance(instance) {
[]
)
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
const getAutoResetPage = useGetLatest(autoResetPage)
useMountedLayoutEffect(() => {
if (getAutoResetPage()) {
dispatch({ type: actions.resetPage })
}
isMountedRef.current = true
}, [dispatch, ...(getResetPageDeps ? getResetPageDeps(instance) : [])])
}, [
dispatch,
manualPagination ? null : data,
manualPagination || manualFilters ? null : filters,
manualPagination || manualGroupBy ? null : groupBy,
manualPagination || manualSortBy ? null : sortBy,
])
const pageCount = manualPagination
? userPageCount
@@ -118,9 +121,6 @@ function useInstance(instance) {
if (manualPagination) {
page = rows
} else {
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getPage')
const pageStart = pageSize * pageIndex
const pageEnd = pageStart + pageSize
@@ -133,7 +133,6 @@ function useInstance(instance) {
return expandRows(page, { manualExpandedKey, expanded, expandSubRows })
}, [
debug,
expandSubRows,
expanded,
manualExpandedKey,
@@ -169,8 +168,7 @@ function useInstance(instance) {
[dispatch]
)
return {
...instance,
Object.assign(instance, {
pageOptions,
pageCount,
page,
@@ -180,7 +178,5 @@ function useInstance(instance) {
previousPage,
nextPage,
setPageSize,
pageIndex,
pageSize,
}
})
}
+119 -70
View File
@@ -1,14 +1,11 @@
import React from 'react'
import { actions, reducerHandlers } from '../hooks/useTable'
import {
actions,
defaultColumn,
getFirstDefined,
mergeProps,
applyPropHooks,
makePropGetter,
useGetLatest,
} from '../utils'
const pluginName = 'useResizeColumns'
import { useConsumeHookGetter } from '../publicUtils'
// Default Column
defaultColumn.canResize = true
@@ -18,8 +15,111 @@ actions.columnStartResizing = 'columnStartResizing'
actions.columnResizing = 'columnResizing'
actions.columnDoneResizing = 'columnDoneResizing'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useResizeColumns = hooks => {
hooks.getResizerProps = [defaultGetResizerProps]
hooks.stateReducers.push(reducer)
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
}
const defaultGetResizerProps = (props, instance, header) => {
const { dispatch } = instance
const onResizeStart = (e, header) => {
let isTouchEvent = false
if (e.type === 'touchstart') {
// lets not respond to multiple touches (e.g. 2 or 3 fingers)
if (e.touches && e.touches.length > 1) {
return
}
isTouchEvent = true
}
const headersToResize = getLeafHeaders(header)
const headerIdWidths = headersToResize.map(d => [d.id, d.totalWidth])
const clientX = isTouchEvent ? Math.round(e.touches[0].clientX) : e.clientX
const dispatchMove = clientXPos => {
dispatch({ type: actions.columnResizing, clientX: clientXPos })
}
const dispatchEnd = () => dispatch({ type: actions.columnDoneResizing })
const handlersAndEvents = {
mouse: {
moveEvent: 'mousemove',
moveHandler: e => dispatchMove(e.clientX),
upEvent: 'mouseup',
upHandler: e => {
document.removeEventListener(
'mousemove',
handlersAndEvents.mouse.moveHandler
)
document.removeEventListener(
'mouseup',
handlersAndEvents.mouse.upHandler
)
dispatchEnd()
},
},
touch: {
moveEvent: 'touchmove',
moveHandler: e => {
if (e.cancelable) {
e.preventDefault()
e.stopPropagation()
}
dispatchMove(e.touches[0].clientX)
return false
},
upEvent: 'touchend',
upHandler: e => {
document.removeEventListener(
handlersAndEvents.touch.moveEvent,
handlersAndEvents.touch.moveHandler
)
document.removeEventListener(
handlersAndEvents.touch.upEvent,
handlersAndEvents.touch.moveHandler
)
dispatchEnd()
},
},
}
const events = isTouchEvent
? handlersAndEvents.touch
: handlersAndEvents.mouse
document.addEventListener(events.moveEvent, events.moveHandler, {
passive: false,
})
document.addEventListener(events.upEvent, events.upHandler, {
passive: false,
})
dispatch({
type: actions.columnStartResizing,
columnId: header.id,
columnWidth: header.totalWidth,
headerIdWidths,
clientX,
})
}
return [
props,
{
onMouseDown: e => e.persist() || onResizeStart(e, header),
onTouchStart: e => e.persist() || onResizeStart(e, header),
style: {
cursor: 'ew-resize',
},
draggable: false,
},
]
}
useResizeColumns.pluginName = 'useResizeColumns'
function reducer(state, action) {
if (action.type === actions.init) {
return {
columnResizing: {
@@ -84,21 +184,12 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useResizeColumns = hooks => {
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
}
useResizeColumns.pluginName = pluginName
const useInstanceBeforeDimensions = instance => {
instance.hooks.getResizerProps = []
const {
flatHeaders,
disableResizing,
hooks: { getHeaderProps },
state: { columnResizing },
dispatch,
} = instance
getHeaderProps.push(() => {
@@ -109,40 +200,12 @@ const useInstanceBeforeDimensions = instance => {
}
})
const onMouseDown = (e, header) => {
const headersToResize = getLeafHeaders(header)
const headerIdWidths = headersToResize.map(d => [d.id, d.totalWidth])
const getInstance = useGetLatest(instance)
const clientX = e.clientX
const onMouseMove = e => {
const clientX = e.clientX
dispatch({ type: actions.columnResizing, clientX })
}
const onMouseUp = e => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
dispatch({ type: actions.columnDoneResizing })
}
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
dispatch({
type: actions.columnStartResizing,
columnId: header.id,
columnWidth: header.totalWidth,
headerIdWidths,
clientX,
})
}
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getResizerPropsHooks = useConsumeHookGetter(
getInstance(),
'getResizerProps'
)
flatHeaders.forEach(header => {
const canResize = getFirstDefined(
@@ -156,27 +219,13 @@ const useInstanceBeforeDimensions = instance => {
header.isResizing = columnResizing.isResizingColumn === header.id
if (canResize) {
header.getResizerProps = userProps => {
return mergeProps(
{
onMouseDown: e => e.persist() || onMouseDown(e, header),
style: {
cursor: 'ew-resize',
},
draggable: false,
},
applyPropHooks(
instanceRef.current.hooks.getResizerProps,
header,
instanceRef.current
),
userProps
)
}
header.getResizerProps = makePropGetter(
getResizerPropsHooks(),
getInstance(),
header
)
}
})
return instance
}
function getLeafHeaders(header) {
+88 -96
View File
@@ -1,12 +1,13 @@
import React from 'react'
import {
mergeProps,
applyPropHooks,
actions,
makePropGetter,
ensurePluginOrder,
safeUseLayoutEffect,
useGetLatest,
useMountedLayoutEffect,
useConsumeHookGetter,
} from '../utils'
import { actions, reducerHandlers } from '../hooks/useTable'
const pluginName = 'useRowSelect'
@@ -15,8 +16,56 @@ actions.resetSelectedRows = 'resetSelectedRows'
actions.toggleRowSelectedAll = 'toggleRowSelectedAll'
actions.toggleRowSelected = 'toggleRowSelected'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useRowSelect = hooks => {
hooks.getToggleRowSelectedProps = [defaultGetToggleRowSelectedProps]
hooks.getToggleAllRowsSelectedProps = [defaultGetToggleAllRowsSelectedProps]
hooks.stateReducers.push(reducer)
hooks.useRows.push(useRows)
hooks.useInstance.push(useInstance)
}
useRowSelect.pluginName = pluginName
const defaultGetToggleRowSelectedProps = (props, instance, row) => {
const { manualRowSelectedKey = 'isSelected' } = instance
let checked = false
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = row.isSelected
}
return [
props,
{
onChange: e => {
row.toggleRowSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked,
title: 'Toggle Row Selected',
},
]
}
const defaultGetToggleAllRowsSelectedProps = (props, instance) => [
props,
{
onChange: e => {
instance.toggleRowSelectedAll(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: instance.isAllRowsSelected,
title: 'Toggle All Rows Selected',
},
]
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
selectedRowPaths: new Set(),
@@ -32,12 +81,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.toggleRowSelectedAll) {
const {
selected,
instanceRef: {
current: { isAllRowsSelected, flatRowPaths },
},
} = action
const { selected } = action
const { isAllRowsSelected, flatRowPaths } = instanceRef.current
const selectAll =
typeof selected !== 'undefined' ? selected : !isAllRowsSelected
@@ -49,13 +94,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.toggleRowSelected) {
const {
path,
selected,
instanceRef: {
current: { flatRowPaths },
},
} = action
const { path, selected } = action
const { flatRowPaths } = instanceRef.current
const key = path.join('.')
const childRowPrefixKey = [key, '.'].join('')
@@ -115,15 +155,6 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useRowSelect = hooks => {
hooks.getToggleRowSelectedProps = []
hooks.getToggleAllRowsSelectedProps = []
hooks.useRows.push(useRows)
hooks.useInstance.push(useInstance)
}
useRowSelect.pluginName = pluginName
function useRows(rows, instance) {
const {
state: { selectedRowPaths },
@@ -146,15 +177,13 @@ function useRows(rows, instance) {
return rows
}
const defaultGetResetSelectedRowPathsDeps = ({ data }) => [data]
function useInstance(instance) {
const {
data,
hooks,
manualRowSelectedKey = 'isSelected',
plugins,
flatRows,
getResetSelectedRowPathsDeps = defaultGetResetSelectedRowPathsDeps,
autoResetSelectedRows = true,
state: { selectedRowPaths },
dispatch,
} = instance
@@ -176,19 +205,13 @@ function useInstance(instance) {
}
}
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
const getAutoResetSelectedRows = useGetLatest(autoResetSelectedRows)
useMountedLayoutEffect(() => {
if (getAutoResetSelectedRows()) {
dispatch({ type: actions.resetSelectedRows })
}
isMountedRef.current = true
}, [
dispatch,
...(getResetSelectedRowPathsDeps
? getResetSelectedRowPathsDeps(instance)
: []),
])
}, [dispatch, data])
const toggleRowSelectedAll = selected =>
dispatch({ type: actions.toggleRowSelectedAll, selected })
@@ -197,71 +220,40 @@ function useInstance(instance) {
dispatch({ type: actions.toggleRowSelected, path, selected })
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const getToggleAllRowsSelectedProps = props => {
return mergeProps(
{
onChange: e => {
toggleRowSelectedAll(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: isAllRowsSelected,
title: 'Toggle All Rows Selected',
},
applyPropHooks(
instanceRef.current.hooks.getToggleAllRowsSelectedProps,
instanceRef.current
),
props
)
}
const getToggleAllRowsSelectedPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleAllRowsSelectedProps'
)
const getToggleAllRowsSelectedProps = makePropGetter(
getToggleAllRowsSelectedPropsHooks(),
getInstance()
)
const getToggleRowSelectedPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleRowSelectedProps'
)
hooks.prepareRow.push(row => {
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
row.getToggleRowSelectedProps = props => {
let checked = false
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = row.isSelected
}
return mergeProps(
{
onChange: e => {
row.toggleRowSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked,
title: 'Toggle Row Selected',
},
applyPropHooks(
instanceRef.current.hooks.getToggleRowSelectedProps,
row,
instanceRef.current
),
props
)
}
return row
row.getToggleRowSelectedProps = makePropGetter(
getToggleRowSelectedPropsHooks(),
getInstance(),
row
)
})
return {
...instance,
Object.assign(instance, {
flatRowPaths,
toggleRowSelected,
toggleRowSelectedAll,
getToggleAllRowsSelectedProps,
isAllRowsSelected,
}
})
}
function getRowIsSelected(row, selectedRowPaths) {
+26 -36
View File
@@ -1,18 +1,24 @@
import React from 'react'
//
import { actions, reducerHandlers } from '../hooks/useTable'
import { functionalUpdate, safeUseLayoutEffect } from '../utils'
const pluginName = 'useRowState'
import {
actions,
functionalUpdate,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
// Actions
actions.setRowState = 'setRowState'
actions.resetRowState = 'resetRowState'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useRowState = hooks => {
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useRowState.pluginName = 'useRowState'
function reducer(state, action) {
if (action.type === actions.init) {
return {
rowState: {},
@@ -42,20 +48,13 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useRowState = hooks => {
hooks.useInstance.push(useInstance)
}
useRowState.pluginName = pluginName
const defaultGetResetRowStateDeps = ({ data }) => [data]
function useInstance(instance) {
const {
hooks,
initialRowStateAccessor,
getResetRowStateDeps = defaultGetResetRowStateDeps,
autoResetRowState = true,
state: { rowState },
data,
dispatch,
} = instance
@@ -92,20 +91,6 @@ function useInstance(instance) {
[setRowState]
)
const rowsMountedRef = React.useRef()
// When data changes, reset row and cell state
safeUseLayoutEffect(() => {
if (rowsMountedRef.current) {
dispatch({ type: actions.resetRowState })
}
rowsMountedRef.current = true
}, [
dispatch,
...(getResetRowStateDeps ? getResetRowStateDeps(instance) : []),
])
hooks.prepareRow.push(row => {
const pathKey = row.path.join('.')
@@ -127,13 +112,18 @@ function useInstance(instance) {
}
})
}
return row
})
return {
...instance,
const getAutoResetRowState = useGetLatest(autoResetRowState)
useMountedLayoutEffect(() => {
if (getAutoResetRowState()) {
dispatch({ type: actions.resetRowState })
}
}, [data])
Object.assign(instance, {
setRowState,
setCellState,
}
})
}
+81 -92
View File
@@ -1,25 +1,61 @@
import React from 'react'
import { ensurePluginOrder, defaultColumn, safeUseLayoutEffect } from '../utils'
import { actions, reducerHandlers } from '../hooks/useTable'
import * as sortTypes from '../sortTypes'
import {
mergeProps,
applyPropHooks,
actions,
ensurePluginOrder,
defaultColumn,
makePropGetter,
useConsumeHookGetter,
getFirstDefined,
defaultOrderByFn,
isFunction,
useGetLatest,
useMountedLayoutEffect,
} from '../utils'
const pluginName = 'useSortBy'
import * as sortTypes from '../sortTypes'
// Actions
actions.resetSortBy = 'resetSortBy'
actions.toggleSortBy = 'toggleSortBy'
actions.clearSortBy = 'clearSortBy'
defaultColumn.sortType = 'alphanumeric'
defaultColumn.sortDescFirst = false
export const useSortBy = hooks => {
hooks.getSortByToggleProps = [defaultGetSortByToggleProps]
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useSortBy.pluginName = 'useSortBy'
const defaultGetSortByToggleProps = (props, instance, column) => {
const { isMultiSortEvent = e => e.shiftKey } = instance
return [
props,
{
onClick: column.canSort
? e => {
e.persist()
column.toggleSortBy(
undefined,
!instance.disableMultiSort && isMultiSortEvent(e)
)
}
: undefined,
style: {
cursor: column.canSort ? 'pointer' : undefined,
},
title: column.canSort ? 'Toggle SortBy' : undefined,
},
]
}
// Reducer
reducerHandlers[pluginName] = (state, action) => {
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
sortBy: [],
@@ -36,7 +72,7 @@ reducerHandlers[pluginName] = (state, action) => {
if (action.type === actions.clearSortBy) {
const { sortBy } = state
const newSortBy = sortBy.filter(d => d.id !== action.columnID)
const newSortBy = sortBy.filter(d => d.id !== action.columnId)
return {
...state,
@@ -45,20 +81,16 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.toggleSortBy) {
const { columnId, desc, multi } = action
const {
columnId,
desc,
multi,
instanceRef: {
current: {
flatColumns,
disableMultiSort,
disableSortRemove,
disableMultiRemove,
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
},
},
} = action
flatColumns,
disableMultiSort,
disableSortRemove,
disableMultiRemove,
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
} = instanceRef.current
const { sortBy } = state
// Find the column for this columnId
@@ -145,46 +177,24 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
defaultColumn.sortType = 'alphanumeric'
defaultColumn.sortDescFirst = false
export const useSortBy = hooks => {
hooks.useInstance.push(useInstance)
}
useSortBy.pluginName = pluginName
function useInstance(instance) {
const {
debug,
data,
rows,
flatColumns,
orderByFn = defaultOrderByFn,
sortTypes: userSortTypes,
manualSorting,
manualSortBy,
defaultCanSort,
disableSortBy,
isMultiSortEvent = e => e.shiftKey,
flatHeaders,
hooks,
state: { sortBy },
dispatch,
plugins,
getResetSortByDeps = false,
autoResetSortBy = true,
} = instance
ensurePluginOrder(plugins, ['useFilters'], 'useSortBy', [])
// Add custom hooks
hooks.getSortByToggleProps = []
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
dispatch({ type: actions.resetSortBy })
}
isMountedRef.current = true
}, [dispatch, ...(getResetSortByDeps ? getResetSortByDeps(instance) : [])])
// Updates sorting based on a columnId, desc flag and multi flag
const toggleSortBy = (columnId, desc, multi) => {
@@ -192,8 +202,12 @@ function useInstance(instance) {
}
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const getSortByTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getSortByToggleProps'
)
// Add the getSortByToggleProps method to columns and headers
flatHeaders.forEach(column => {
@@ -223,31 +237,11 @@ function useInstance(instance) {
}
}
column.getSortByToggleProps = props => {
return mergeProps(
{
onClick: canSort
? e => {
e.persist()
column.toggleSortBy(
undefined,
!instanceRef.current.disableMultiSort && isMultiSortEvent(e)
)
}
: undefined,
style: {
cursor: canSort ? 'pointer' : undefined,
},
title: 'Toggle SortBy',
},
applyPropHooks(
instanceRef.current.hooks.getSortByToggleProps,
column,
instanceRef.current
),
props
)
}
column.getSortByToggleProps = makePropGetter(
getSortByTogglePropsHooks(),
getInstance(),
column
)
const columnSort = sortBy.find(d => d.id === id)
column.isSorted = !!columnSort
@@ -256,11 +250,9 @@ function useInstance(instance) {
})
const sortedRows = React.useMemo(() => {
if (manualSorting || !sortBy.length) {
if (manualSortBy || !sortBy.length) {
return rows
}
if (process.env.NODE_ENV !== 'production' && debug)
console.time('getSortedRows')
// Filter out sortBys that correspond to non existing columns
const availableSortBy = sortBy.filter(sort =>
@@ -331,24 +323,21 @@ function useInstance(instance) {
return sortedData
}
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('getSortedRows')
return sortData(rows)
}, [
manualSorting,
sortBy,
debug,
rows,
flatColumns,
orderByFn,
userSortTypes,
])
}, [manualSortBy, sortBy, rows, flatColumns, orderByFn, userSortTypes])
return {
...instance,
const getAutoResetSortBy = useGetLatest(autoResetSortBy)
useMountedLayoutEffect(() => {
if (getAutoResetSortBy()) {
dispatch({ type: actions.resetSortBy })
}
}, [manualSortBy ? null : data])
Object.assign(instance, {
toggleSortBy,
rows: sortedRows,
preSortedRows: rows,
}
sortedRows,
rows: sortedRows,
})
}
+222
View File
@@ -0,0 +1,222 @@
import React from 'react'
export const actions = {
init: 'init',
}
export const defaultColumn = {
Cell: ({ cell: { value = '' } }) => String(value),
width: 150,
minWidth: 0,
maxWidth: Number.MAX_SAFE_INTEGER,
}
export function defaultOrderByFn(arr, funcs, dirs) {
return [...arr].sort((rowA, rowB) => {
for (let i = 0; i < funcs.length; i += 1) {
const sortFn = funcs[i]
const desc = dirs[i] === false || dirs[i] === 'desc'
const sortInt = sortFn(rowA, rowB)
if (sortInt !== 0) {
return desc ? -sortInt : sortInt
}
}
return dirs[0] ? rowA.index - rowB.index : rowB.index - rowA.index
})
}
export function defaultGroupByFn(rows, columnId) {
return rows.reduce((prev, row, i) => {
// TODO: Might want to implement a key serializer here so
// irregular column values can still be grouped if needed?
const resKey = `${row.values[columnId]}`
prev[resKey] = Array.isArray(prev[resKey]) ? prev[resKey] : []
prev[resKey].push(row)
return prev
}, {})
}
function mergeProps(...propList) {
return propList.reduce((props, next) => {
const { style, className, ...rest } = next
props = {
...props,
...rest,
style: {
...(props.style || {}),
...(style || {}),
},
className: [props.className, className].filter(Boolean).join(' '),
}
if (props.className === '') {
delete props.className
}
return props
}, {})
}
function handlePropGetter(prevProps, userProps, ...meta) {
// Handle a lambda, pass it the previous props
if (typeof userProps === 'function') {
return handlePropGetter({}, userProps(prevProps, ...meta))
}
// Handle an array, merge each item as separate props
if (Array.isArray(userProps)) {
return mergeProps(prevProps, ...userProps)
}
// Handle an object by default, merge the two objects
return mergeProps(prevProps, userProps)
}
export const makePropGetter = (hooks, ...meta) => {
return (userProps = {}) =>
[...hooks, userProps].reduce(
(prev, next) => handlePropGetter(prev, next, ...meta),
{}
)
}
export const reduceHooks = (hooks, initial, ...args) =>
hooks.reduce((prev, next) => {
const nextValue = next(prev, ...args)
if (process.env.NODE_ENV !== 'production') {
if (typeof nextValue === 'undefined') {
console.info(next)
throw new Error(
'React Table: A reducer hook ☝️ just returned undefined! This is not allowed.'
)
}
}
return nextValue
}, initial)
export const loopHooks = (hooks, ...args) =>
hooks.forEach(hook => {
const nextValue = hook(...args)
if (process.env.NODE_ENV !== 'production') {
if (typeof nextValue !== 'undefined') {
console.info(hook, nextValue)
throw new Error(
'React Table: A loop-type hook ☝️ just returned a value! This is not allowed.'
)
}
}
})
export function ensurePluginOrder(plugins, befores, pluginName, afters) {
const pluginIndex = plugins.findIndex(
plugin => plugin.pluginName === pluginName
)
if (pluginIndex === -1) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(`The plugin "${pluginName}" was not found in the plugin list!
This usually means you need to need to name your plugin hook by setting the 'pluginName' property of the hook function, eg:
${pluginName}.pluginName = '${pluginName}'
`)
}
}
befores.forEach(before => {
const beforeIndex = plugins.findIndex(
plugin => plugin.pluginName === before
)
if (beforeIndex > -1 && beforeIndex > pluginIndex) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed after the ${before} plugin hook!`
)
}
}
})
afters.forEach(after => {
const afterIndex = plugins.findIndex(plugin => plugin.pluginName === after)
if (process.env.NODE_ENV !== 'production') {
if (afterIndex > -1 && afterIndex < pluginIndex) {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed before the ${after} plugin hook!`
)
}
}
})
}
export function functionalUpdate(updater, old) {
return typeof updater === 'function' ? updater(old) : updater
}
export function useGetLatest(obj) {
const ref = React.useRef()
ref.current = obj
return React.useCallback(() => ref.current, [])
}
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
export const safeUseLayoutEffect =
typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect
export function useMountedLayoutEffect(fn, deps) {
const mountedRef = React.useRef(false)
safeUseLayoutEffect(() => {
if (mountedRef.current) {
fn()
}
mountedRef.current = true
// eslint-disable-next-line
}, deps)
}
export function useAsyncDebounce(defaultFn, defaultWait = 0) {
const debounceRef = React.useRef({})
debounceRef.current.defaultFn = defaultFn
debounceRef.current.defaultWait = defaultWait
const debounce = React.useCallback(
async (
fn = debounceRef.current.defaultFn,
wait = debounceRef.current.defaultWait
) => {
if (!debounceRef.current.promise) {
debounceRef.current.promise = new Promise((resolve, reject) => {
debounceRef.current.resolve = resolve
debounceRef.current.reject = reject
})
}
if (debounceRef.current.timeout) {
clearTimeout(debounceRef.current.timeout)
}
debounceRef.current.timeout = setTimeout(async () => {
delete debounceRef.current.timeout
try {
debounceRef.current.resolve(await fn())
} catch (err) {
debounceRef.current.reject(err)
} finally {
delete debounceRef.current.promise
}
}, wait)
return debounceRef.current.promise
},
[]
)
return debounce
}
export function useConsumeHookGetter(hooks, hookName) {
const getter = useGetLatest(hooks[hookName])
hooks[hookName] = undefined
return getter
}
+21 -168
View File
@@ -1,18 +1,7 @@
import React from 'react'
import { defaultColumn } from './publicUtils'
export const defaultColumn = {
Cell: ({ cell: { value = '' } }) => String(value),
show: true,
width: 150,
minWidth: 0,
maxWidth: Number.MAX_SAFE_INTEGER,
}
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
export const safeUseLayoutEffect =
typeof window !== 'undefined' && process.env.NODE_ENV === 'production'
? React.useLayoutEffect
: React.useEffect
export * from './publicUtils'
// Find the depth of the columns
export function findMaxDepth(columns, depth = 0) {
@@ -24,13 +13,7 @@ export function findMaxDepth(columns, depth = 0) {
}, 0)
}
export function decorateColumn(
column,
userDefaultColumn,
parent,
depth,
index
) {
function decorateColumn(column, userDefaultColumn, parent, depth, index) {
// Apply the userDefaultColumn
column = { ...defaultColumn, ...userDefaultColumn, ...column }
@@ -60,6 +43,7 @@ export function decorateColumn(
column = {
// Make sure there is a fallback header, just in case
Header: () => <>&nbsp;</>,
Footer: () => <>&nbsp;</>,
...column,
// Materialize and override this stuff
id,
@@ -176,45 +160,24 @@ export function makeHeaderGroups(flatColumns, defaultColumn) {
return headerGroups.reverse()
}
export function determineHeaderVisibility(instance) {
const { headers } = instance
const handleColumn = (column, parentVisible) => {
column.isVisible = parentVisible
? typeof column.show === 'function'
? column.show(instance)
: !!column.show
: false
let totalVisibleHeaderCount = 0
if (column.headers && column.headers.length) {
column.headers.forEach(
subColumn =>
(totalVisibleHeaderCount += handleColumn(subColumn, column.isVisible))
)
} else {
totalVisibleHeaderCount = column.isVisible ? 1 : 0
}
column.totalVisibleHeaderCount = totalVisibleHeaderCount
return totalVisibleHeaderCount
}
let totalVisibleHeaderCount = 0
headers.forEach(
subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
)
}
const pathObjCache = new Map()
export function getBy(obj, path, def) {
if (!path) {
return obj
}
const pathObj = makePathArray(path)
const cacheKey = typeof path === 'function' ? path : JSON.stringify(path)
const pathObj =
pathObjCache.get(cacheKey) ||
(() => {
const pathObj = makePathArray(path)
pathObjCache.set(cacheKey, pathObj)
return pathObj
})()
let val
try {
val = pathObj.reduce((cursor, pathPart) => cursor[pathPart], obj)
} catch (e) {
@@ -223,20 +186,6 @@ export function getBy(obj, path, def) {
return typeof val !== 'undefined' ? val : def
}
export function defaultOrderByFn(arr, funcs, dirs) {
return [...arr].sort((rowA, rowB) => {
for (let i = 0; i < funcs.length; i += 1) {
const sortFn = funcs[i]
const desc = dirs[i] === false || dirs[i] === 'desc'
const sortInt = sortFn(rowA, rowB)
if (sortInt !== 0) {
return desc ? -sortInt : sortInt
}
}
return dirs[0] ? rowA.index - rowB.index : rowB.index - rowA.index
})
}
export function getFirstDefined(...args) {
for (let i = 0; i < args.length; i += 1) {
if (typeof args[i] !== 'undefined') {
@@ -245,17 +194,6 @@ export function getFirstDefined(...args) {
}
}
export function defaultGroupByFn(rows, columnId) {
return rows.reduce((prev, row, i) => {
// TODO: Might want to implement a key serializer here so
// irregular column values can still be grouped if needed?
const resKey = `${row.values[columnId]}`
prev[resKey] = Array.isArray(prev[resKey]) ? prev[resKey] : []
prev[resKey].push(row)
return prev
}, {})
}
export function getElementDimensions(element) {
const rect = element.getBoundingClientRect()
const style = window.getComputedStyle(element)
@@ -303,56 +241,6 @@ function isReactComponent(component) {
return isClassComponent(component) || isFunctionComponent(component)
}
export const mergeProps = (...groups) => {
let props = {}
groups.forEach(({ style = {}, className, ...rest } = {}) => {
props = {
...props,
...rest,
style: {
...(props.style || {}),
...style,
},
className: [props.className, className].filter(Boolean).join(' '),
}
})
if (props.className === '') {
delete props.className
}
return props
}
export const applyHooks = (hooks, initial, ...args) =>
hooks.reduce((prev, next) => {
const nextValue = next(prev, ...args)
if (typeof nextValue === 'undefined') {
throw new Error(
'React Table: A hook just returned undefined! This is not allowed.'
)
}
return nextValue
}, initial)
export const applyPropHooks = (hooks, ...args) =>
hooks.reduce((prev, next) => mergeProps(prev, next(...args)), {})
export const warnUnknownProps = props => {
if (Object.keys(props).length) {
throw new Error(
`Unknown options passed to useReactTable:
${JSON.stringify(props, null, 2)}`
)
}
}
export function sum(arr) {
return arr.reduce((prev, curr) => prev + curr, 0)
}
export function isFunction(a) {
if (typeof a === 'function') {
return a
@@ -377,40 +265,6 @@ export function flattenBy(columns, childKey) {
return flatColumns
}
export function ensurePluginOrder(plugins, befores, pluginName, afters) {
const pluginIndex = plugins.findIndex(
plugin => plugin.pluginName === pluginName
)
if (pluginIndex === -1) {
throw new Error(`The plugin ${pluginName} was not found in the plugin list!
This usually means you need to need to name your plugin hook by setting the 'pluginName' property of the hook function, eg:
${pluginName}.pluginName = '${pluginName}'
`)
}
befores.forEach(before => {
const beforeIndex = plugins.findIndex(
plugin => plugin.pluginName === before
)
if (beforeIndex > -1 && beforeIndex > pluginIndex) {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed after the ${before} plugin hook!`
)
}
})
afters.forEach(after => {
const afterIndex = plugins.findIndex(plugin => plugin.pluginName === after)
if (afterIndex > -1 && afterIndex < pluginIndex) {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed before the ${after} plugin hook!`
)
}
})
}
export function expandRows(
rows,
{ manualExpandedKey, expanded, expandSubRows = true }
@@ -438,12 +292,11 @@ export function expandRows(
return expandedRows
}
export function functionalUpdate(updater, old) {
return typeof updater === 'function' ? updater(old) : updater
}
//
const reOpenBracket = /\[/g
const reCloseBracket = /\]/g
function makePathArray(obj) {
return (
flattenDeep(obj)
@@ -452,8 +305,8 @@ function makePathArray(obj) {
// join parts using period
.join('.')
// replace brackets with periods
.replace(/\[/g, '.')
.replace(/\]/g, '')
.replace(reOpenBracket, '.')
.replace(reCloseBracket, '')
// split it back out on periods
.split('.')
)