Compare commits

...
184 Commits
Author SHA1 Message Date
Tanner Linsley 379d9e11d5 v6.9.0 2019-01-31 10:18:22 -07:00
John MaguireandTanner Linsley 3fff682578 apply @twheys PR #1077 as patch and update Array.concat to [].concat (#1241) 2019-01-31 10:15:09 -07:00
Josh McCulloughandTanner Linsley 168a8e3f93 update fireFetchData to use current state for select value (#1231) 2019-01-31 10:09:28 -07:00
Josh McCulloughandTanner Linsley 221164484f cleanup all but one linting issue (#1232) 2019-01-31 10:08:31 -07:00
Andrej GajdosandTanner Linsley c7d2c36454 adding position prop into pagination component (#1205)
- adding isTop prop into pagination component, which allows
differentiate if pagination is on top or bottom of the table
2019-01-31 10:08:06 -07:00
Laurent PandTanner Linsley 26961d0994 [fix] filter data on all available columns not just visible one (#1148) 2019-01-31 10:07:06 -07:00
Devin ClarkandTanner Linsley de6389cafc Adding IDs for select table, fixing backwards compatibility on floating left checkbox (#1208)
* Adding IDs for select all and individual row checkboxes

* Using keyfield const
2019-01-31 10:06:47 -07:00
Rahul VermaandTanner Linsley e0f9d98819 Adds aria-label prop to checkboxes (#1191) 2019-01-31 10:05:15 -07:00
Grzegorz RozdzialikandTanner Linsley 0365057446 Extract pagination elements renderers to pagination props (#1176)
Pagination elements are now customizable without having
to create a new Pagination component, that would
mostly mimic the existing one in terms of functionality.
2019-01-31 10:03:27 -07:00
StevenandTanner Linsley ec25bfbb5a fixed the sanbox code issue (#1174)
* fixed the sabox code issue

* add --copy-files flag to copy ti svg files to lib folder
2019-01-31 10:02:41 -07:00
Evan BrodieandTanner Linsley 0a1c12faca Adds import instructions to the HOC README (#1168)
* Adds import instructions to the HOC README

Also fixes up some language and remove other import instructions. It's better to just have the import instructions in just one place.

* Better visualizes a list of functions
2019-01-31 10:02:12 -07:00
AndyandTanner Linsley 1fddb1b97d Example code fixed with missing return statement (#1154) 2019-01-31 10:01:58 -07:00
Tanner Linsley 1e04377de7 Update README.md 2019-01-28 14:55:32 -07:00
Tanner Linsley 555c4fae9d Update README.md 2019-01-28 14:35:05 -07:00
Tanner Linsley 0d8ca53b76 Update README.md 2019-01-28 14:34:04 -07:00
Tanner Linsley 64db8e09d4 Update .gitignore 2019-01-28 13:47:31 -07:00
Tanner LinsleyandGitHub c5233c4404 Update README.md 2019-01-16 08:56:50 -07:00
Tanner LinsleyandGitHub d0d862f1e8 Add files via upload 2019-01-16 08:55:42 -07:00
Tanner LinsleyandGitHub dd3f30b099 Update bug_report.md 2018-10-04 14:55:20 -06:00
Tanner LinsleyandGitHub d5fc894dd7 Delete ISSUE_TEMPLATE.md 2018-10-04 14:54:16 -06:00
Tanner Linsley dc771ff25f Update issue templates 2018-10-04 14:53:51 -06:00
simjohandTanner Linsley d38021d4b0 Updated ReadMe with some more Props (#1142)
I found the added Props by looking into the defaultProps.js when I could not find a way change the styling of the filter row.
Custom Props
Built-in Components
Every single built-in component's props can be dynamically extended using any one of these prop-callbacks:

<ReactTable
  getProps={fn}
  getTableProps={fn}
  getTheadGroupProps={fn}
  getTheadGroupTrProps={fn}
  getTheadGroupThProps={fn}
  getTheadProps={fn}
  getTheadTrProps={fn}
  getTheadThProps={fn}
  +getTheadFilterProps={fn}
  +getTheadFilterTrProps={fn}
  +getTheadFilterThProps={fn}
2018-10-04 14:51:28 -06:00
Jannik KeyeandTanner Linsley 06648b2577 feature: allow minResizeWidth to be set (#1135)
* feature: allow minResizeWidth to be set

* fix: add minResizeWidth propType
2018-10-04 14:49:11 -06:00
Leonardo MerzaandTanner Linsley 836f256031 added closeExpanded function to subComponent callback (#1121) 2018-10-04 14:48:18 -06:00
Colton ColcleasureandTanner Linsley 188fc51336 Fixed defaultProps.selectType. (#1129)
Changed defaultProps.selectType from "check" to "checkbox".
2018-10-04 14:47:49 -06:00
tragessereandTanner Linsley 474244ce41 Pagination accessibility (#1127)
* Add aria-label attributes to pagination jump and row count selector with a new prop to specify different text.

* Add new text props for labels to README
2018-10-04 14:47:30 -06:00
Jakub ŻurawskiandTanner Linsley b6074a9ab1 Accesibility improvement - add role to tr in treeTable (#1114) 2018-10-04 14:45:40 -06:00
Mohamed NimirandTanner Linsley 3278e1b05e Update README.md (#1086)
Fixed server-side data bad example link to point to https://react-table.js.org/#/story/server-side-data instead of 404 link https://github.com/react-tools/react-table/blob/master/stories/ServerSide.js

Fixes #929
2018-10-04 14:44:15 -06:00
Alec ReserandTanner Linsley 2352cac4b8 Added placeholder to filter input. (#1087)
* Added placeholder to filter input.

* Changed package.json version.
2018-10-04 14:42:59 -06:00
Robin PhamandTanner Linsley d94f59a5fa only update state if page prop changes (#1082) 2018-10-04 14:42:37 -06:00
Jeremy LibermanandTanner Linsley 7876a3876c Resolve "cannot call class as a function" error (#1050)
When rendering a class component using the `class extends React.Component {}` syntax, you would get an error `TypeError: Cannot call a class as a function` because the check to determine whether a component was a class component was insufficient. It seems pointless to even have a check, however, because the JSX syntax can render both class and functional components.
2018-10-04 14:42:16 -06:00
maxime romaandTanner Linsley 02e65b4388 fix linter , update selectTable hoc (#1073)
* fix lint on foldable file add options to choose postion of checkbox
column

* (update hoc): selecttable options parameters position
2018-10-04 14:41:24 -06:00
Shubham KanodiaandTanner Linsley d9d49fa3de Adds "prop-types" as a peerDependency (#1069)
* Adds "prop-types" as a peerDependency

* Removed trailling comma
2018-10-04 14:40:13 -06:00
Kyle HallemanandTanner Linsley 41784cd52d allow rest props from getTfootProps for TfootComponent (#1035) 2018-10-04 14:39:48 -06:00
Mayank JethvaandTanner Linsley 9048835bcc ReactTable HOC: advancedExpandTable (#1000)
* initial commit

* update readme

* update examples and src

* edit readme

* use single instance of advancedExpandTable

* add in hoc codesandbox to docs, run eslint on new source file
2018-10-04 14:39:07 -06:00
Bret IkeharaandTanner Linsley b12fc8fc88 remove space in Logo name (#1033) 2018-10-04 14:38:33 -06:00
Krzysztof KaczmarczykandTanner Linsley 76fde77b0f Add additional column's renderers in TreeTable HOC (#1029)
Pass Expander, PivotValue and Pivot renderers to to column constructor in TreeTable HOC
2018-10-04 14:37:44 -06:00
smoleniuchandTanner Linsley f50b0a47cf SelectTable - Make input component type defaults to checkbox (#1021) 2018-10-04 14:37:19 -06:00
Don PflasterandTanner Linsley ac8b497671 Tree uses accessor or ID and always shows pivot cells (#1011)
* Also check ID field when finding pivot col in treeTableHOC

* Pass the ID if you've got one on treeTableHOC

* An expandable cell should never be hidden
2018-10-04 14:36:46 -06:00
Rebekah Heacock JonesandTanner Linsley c79806090a Fix propTypes validation for getFooterProps (#1007)
This should be a function (like the other getXProps), not an object
2018-10-04 14:36:20 -06:00
Tanner Linsley f55ce62041 Merge branch 'master' of https://github.com/react-tools/react-table 2018-05-29 10:56:34 -06:00
Mario ViensandTanner Linsley 4c9b44ab48 documentation formatting fix (#986) 2018-05-28 01:11:35 -06:00
Tanner Linsley 48869a65e7 Better issue template 2018-05-24 17:00:17 -06:00
emyarodandTanner Linsley 3246336120 Add cross-env package (#873)
* Fix typo

* Edit link to working codesandbox

Fix '100k Rows w/ Pivoting & Sub Components' example

Closes #870

* Add cross-env to remove environment variable errors on Windows
2018-05-24 16:36:37 -06:00
Efim PasianidiandTanner Linsley b12238d535 Add defaultPage prop (#941)
* add defaultPage prop

* fix defaultPage in manual mode
2018-05-24 16:36:19 -06:00
Mark McDonaldandTanner Linsley 1f92ed8d4f Add more documentation for overriding props (#975)
I think this is the most common way of setting columns or expanderDefaults.

I had to find issue #565 and then follow it to issue #394 to see explanations on how to do this.
2018-05-24 16:35:22 -06:00
TerryLeeandTanner Linsley cf59c644b4 Just correct names of parameters for onFilteredChanged (#967) 2018-05-24 16:33:09 -06:00
Steve SharpandTanner Linsley a7e8e26c00 Update README.md (#973)
Fixes typo
2018-05-24 16:32:50 -06:00
StevenandTanner Linsley dd4c1e2df6 add FoldableTable (#937)
I have used this library to develop a big application for my company and had been required to make the columns are foldable. I saw that feature is useful and would like to share with everybody. Especially to all developers who developed this great component.

Let me know if any issues with My component. I will fix it accordingly.
2018-05-24 16:32:34 -06:00
Anthon FredrikssonandTanner Linsley 621c3bf092 Fixed text mismatch when doing SSR (#957)
* fixed a mismatch issue when doing ssr. made some windows-specific changes to ease contributing

* remove accidentally committed file
2018-05-24 16:27:57 -06:00
Bill FienbergandTanner Linsley 72afabbd03 Fix README: defaultSortMethod doesn't match code (#910)
Updating the `defaultSortMethod` in the README to match the [code](https://github.com/react-tools/react-table/blob/3a8a037ee68b11e329c581a8d61a37db276a0dbf/src/defaultProps.js#L46)
2018-05-24 16:25:57 -06:00
Stuart CasarottoandTanner Linsley 4aa07c33da Typo (#899)
arra -> array
2018-05-24 16:25:41 -06:00
Frank NguyenandTanner Linsley d430d51888 Added react-dom as a peer dependency (#889) 2018-05-24 16:25:28 -06:00
AndrewandTanner Linsley 4824b4c8cc Remove header focus outline. Fixes react-tools/react-table#685 (#881) 2018-05-24 16:24:54 -06:00
Richard AandTanner Linsley 60766cf261 Add prefix to key of pad rows (#828)
Add prefix to key of pad rows so it doesn't conflict with keys of page rows.
Duplicate keys are causing rendering issues with preact.
2018-05-24 16:23:53 -06:00
Tanner Linsley fcdc3d88bc v6.8.6 2018-05-24 10:24:29 -06:00
Tanner Linsley 24a9efd670 v6.8.5 2018-05-19 00:47:17 -06:00
Tanner Linsley bdb7d44438 v6.8.4 2018-05-18 17:34:41 -06:00
Tanner Linsley 7a6ed50b81 Make data prop required, but allow it to be anything. 2018-05-18 17:34:03 -06:00
Tanner Linsley 8f062550aa v6.8.3 2018-05-18 17:32:04 -06:00
Ben BermanandTanner Linsley 4e9eec3578 Remove ellipsis from default expander table header (#920) 2018-04-19 18:48:52 -06:00
Tanner Linsley 35b92567b5 v6.8.2 2018-04-17 15:14:45 -06:00
Tanner Linsley a1f5b462d5 Revert mistaken removal of rt-resizable-header-content div 2018-04-17 15:14:05 -06:00
Tanner Linsley 9e479e4d4c v6.8.1 2018-04-17 12:23:59 -06:00
Tanner Linsley 9fe806d8a7 Update Eslint and Code Formatting 2018-04-17 12:22:34 -06:00
Tanner Linsley 083534149c Version Update 2018-04-17 12:15:50 -06:00
Gary MenzelandTanner Linsley 8bd3daafcb Doco updates (#680)
* Merge fork from master (#6)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Fork Update (#7)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Update README.md (#584)

* Update README.md

Missing " on Features list,
Extra comma removed

* Update README.md

Added space for component uniformity.

* Update the devDependencies for the linter (#596)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix ThComponent classnames ordering (#673)

Allow for custom classname to overwrite base styles

* Add column to getResizerProps (#667)

* CHANGELOG update

* Doco updates

fixed a typo - ‘row’ to ‘original’
added minimal dock on ‘minRows’

* Merge from original (#9)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Update README.md (#584)

* Update README.md

Missing " on Features list,
Extra comma removed

* Update README.md

Added space for component uniformity.

* Update the devDependencies for the linter (#596)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix ThComponent classnames ordering (#673)

Allow for custom classname to overwrite base styles

* Add column to getResizerProps (#667)

* CHANGELOG update for 6.7.5 (#679)

* Merge fork from master (#6)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Fork Update (#7)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Update README.md (#584)

* Update README.md

Missing " on Features list,
Extra comma removed

* Update README.md

Added space for component uniformity.

* Update the devDependencies for the linter (#596)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix ThComponent classnames ordering (#673)

Allow for custom classname to overwrite base styles

* Add column to getResizerProps (#667)

* CHANGELOG update
2018-02-08 09:58:58 -07:00
Shaun SweetandTanner Linsley 6649b21abe docs: add select HOC docs to better document how to use the HOC (#733) 2018-02-08 09:58:24 -07:00
Jeremy WoodandTanner Linsley 3a8a037ee6 Implemented basic aria roles following grid pattern. (#758) 2018-02-08 09:57:33 -07:00
Catalin BertaandTanner Linsley 9e0361e511 Move hard coded select width to prop (#761) 2018-02-08 09:56:17 -07:00
Pavel GavlíkandTanner Linsley 0a62d86e5e Fix style prop not being properly used in ReactTablePagination component (#785) 2018-02-08 09:55:38 -07:00
Bertrand MarronandTanner Linsley 3ff988861e Improve build process (#792)
* Use preset-env instead of preset-es2015

Remove preset-stage-2 and use individual required plugins.

* Expose es module build

* Update scripts in package.json

* Use rollup for faster and lighter umd builds

Add non minified version of the build.
2018-02-08 09:55:16 -07:00
Tanner LinsleyandGitHub f4067b86dd Update README.md 2018-02-08 09:52:49 -07:00
Tanner Linsley f70d453caa v6.7.6 2017-12-21 15:15:32 -07:00
Gary MenzelandGitHub 54f3cc791c Focus bug (#686)
* Merge fork from master (#6)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Fork Update (#7)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Update README.md (#584)

* Update README.md

Missing " on Features list,
Extra comma removed

* Update README.md

Added space for component uniformity.

* Update the devDependencies for the linter (#596)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix ThComponent classnames ordering (#673)

Allow for custom classname to overwrite base styles

* Add column to getResizerProps (#667)

* CHANGELOG update

* Header focus bug fix

Fixes #685
2017-12-20 08:27:35 +11:00
Gary MenzelandTanner Linsley 05c56f0da4 CHANGELOG update for 6.7.5 (#679)
* Merge fork from master (#6)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Fork Update (#7)

* Examples Refactor + multiSort flag (#619)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Docs testing cleanup (#645)

* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Update README.md (#584)

* Update README.md

Missing " on Features list,
Extra comma removed

* Update README.md

Added space for component uniformity.

* Update the devDependencies for the linter (#596)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix ThComponent classnames ordering (#673)

Allow for custom classname to overwrite base styles

* Add column to getResizerProps (#667)

* CHANGELOG update
2017-12-12 16:44:17 -07:00
Simon AngellandTanner Linsley ddf877bcac Add column to getResizerProps (#667) 2017-12-12 15:09:23 -08:00
Edward BramantiandTanner Linsley 928ad11a07 Fix ThComponent classnames ordering (#673)
Allow for custom classname to overwrite base styles
2017-12-12 15:05:31 -08:00
Will OlsonandTanner Linsley 0783837786 Update the devDependencies for the linter (#596)
* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors
2017-12-12 14:56:51 -08:00
Amir ShresthaandTanner Linsley cf0f8bb729 Update README.md (#584)
* Update README.md

Missing " on Features list,
Extra comma removed

* Update README.md

Added space for component uniformity.
2017-12-12 14:54:23 -08:00
Gary MenzelandGitHub 1e849df999 Merge branch 'master' into master 2017-11-27 14:08:05 +11:00
Gary MenzelandGitHub 62da8880e6 Docs testing cleanup (#645)
* Examples Refactor + multiSort flag (#619) (#4)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update

* Examples Refactor + multiSort flag (#619) (#5)

* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update
2017-11-27 13:47:58 +11:00
Gary Menzel 656522eb71 Comment out 2017-11-27 12:33:58 +11:00
Gary MenzelandGitHub b0c50509ee Examples Refactor + multiSort flag (#619) (#5)
* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update
2017-11-27 12:32:18 +11:00
Gary MenzelandGitHub 01ca4518fc Examples Refactor + multiSort flag (#619) (#4)
* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update
2017-11-27 09:57:12 +11:00
Gary MenzelandGitHub cdf806b3f6 Merge branch 'master' into master 2017-11-27 09:56:49 +11:00
Gary Menzel 0443644ccd Fixes #643
Still requires some basic sanity test to ensure ReactTable does
not have any fundamental coding errors.
Modified some of the /docs code to help with manual testing.
2017-11-27 09:50:36 +11:00
Gary MenzelandGitHub f74ba3cc16 Examples Refactor + multiSort flag (#619)
* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid

* Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)

* Refactor complete
May need to remove some redundant code

* Text change for the HOC samples

* Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.

* refactor: Fix defaultProps.js linter errors

* refactor: Fix lifecycle.js linter errors

* refactor: Fix pagination.js linter errors

* refactor: Fix propTypes.js linter errors

* refactor: Fix utils.js linter errors

* refactor: Fix methods.js linter errors

* refactor: Fix index.js linter errors

* Fix for linter changes + CHANGELOG update
2017-11-23 15:30:07 +11:00
Gary Menzel 2e8596618a Fix for linter changes + CHANGELOG update 2017-11-23 13:53:00 +11:00
Gary MenzelandGitHub b2db31c9bd Merge pull request #3 from frankolson/linter_dependencies
Linter dependencies
2017-11-23 13:45:41 +11:00
Gary MenzelandGitHub 6a5400b247 Merge branch 'master' into linter_dependencies 2017-11-23 13:45:25 +11:00
Will Olson ed6dd5af4c refactor: Fix index.js linter errors 2017-11-22 10:04:26 -08:00
Will Olson 80aa2ea7f4 refactor: Fix methods.js linter errors 2017-11-22 09:48:13 -08:00
Will Olson b310a2ebc4 refactor: Fix utils.js linter errors 2017-11-22 09:33:10 -08:00
Will Olson bcfa658257 refactor: Fix propTypes.js linter errors 2017-11-22 09:19:36 -08:00
Will Olson ad151b5ff0 refactor: Fix pagination.js linter errors 2017-11-22 09:17:21 -08:00
Will Olson 3f1b0d36ed refactor: Fix lifecycle.js linter errors 2017-11-22 09:13:59 -08:00
Will Olson a6036004af refactor: Fix defaultProps.js linter errors 2017-11-22 09:07:26 -08:00
Will Olson 913d214e94 Merge branch 'master' into linter_dependencies 2017-11-22 08:59:08 -08:00
Gary MenzelandGitHub 2fbd0d49db Merge branch 'master' into master 2017-11-16 09:31:31 +11:00
Gary Menzel fc47d4f258 Introduced a 'multiSort' flag
Defaults to 'true'
A 'false' value will turn multi-sort off.
2017-11-16 03:05:44 +11:00
Gary Menzel 6df336215d Text change for the HOC samples 2017-11-15 20:54:29 +11:00
Gary Menzel feec96359b Refactor complete
May need to remove some redundant code
2017-11-15 20:43:29 +11:00
Gary Menzel 33252adfab Refactor HOCs to /src/hoc
Still have to write the HOCReadme.md (still just a placeholder for now)
2017-11-14 15:38:50 +11:00
Gary MenzelandTanner Linsley 1cf9e49952 Example HOCs for TreeTable and CheckboxTable (#609)
* chore: Update the devDependencies for the linter

* A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.

* Missing dependency - shortid
2017-11-12 15:13:05 -07:00
Gary Menzel b585c4b8db Missing dependency - shortid 2017-11-13 08:09:45 +11:00
Gary Menzel 710891f0c0 A few HOC examples for react-table.
Not really integrated with the whole codesandbox.io approach.
2017-11-12 16:32:29 +11:00
Gary MenzelandGitHub cb0000e588 Merge pull request #2 from frankolson/linter_dependencies
chore: Update the devDependencies for the linter
2017-11-03 22:11:22 +11:00
Gary MenzelandGitHub d0bd56729b Merge pull request #1 from react-tools/master
Update to 6.7.4 from original
2017-11-03 21:47:52 +11:00
Will Olson e4c819039f chore: Update the devDependencies for the linter 2017-11-02 11:54:53 -07:00
Tanner Linsley adc07de817 6.7.4 2017-10-27 14:55:17 -06:00
Tanner Linsley e94e88849a Fix Prop types for columns 2017-10-27 14:55:11 -06:00
Tanner Linsley 2dcfef884f 6.7.3 2017-10-27 14:27:24 -06:00
Tanner Linsley d798584208 Fix the rest of the proptypes 2017-10-27 14:27:20 -06:00
Tanner Linsley 5759885983 6.7.2 2017-10-27 14:23:07 -06:00
Tanner Linsley e59ddc1f8d Fix getPropTypes proptype check 2017-10-27 14:23:03 -06:00
Tanner Linsley 35e8636fd1 6.7.1
Fixes #582
2017-10-27 13:45:06 -06:00
Tanner Linsley bb2f969db9 Fix: eslint-config moved to dev deps 2017-10-27 13:44:38 -06:00
Tanner Linsley cd0222fcd2 6.7.0 2017-10-27 13:02:40 -06:00
Tanner Linsley 93ceffbf26 6.7.0-alpha-0 2017-10-27 13:00:57 -06:00
Tanner Linsley 879a6ac273 Deps, linting, and style upgrades 2017-10-27 13:00:54 -06:00
Tanner Linsley b285288849 Merge branch 'master' of https://github.com/react-tools/react-table 2017-10-27 12:14:50 -06:00
Aaron FreidusandTanner Linsley 05f4aaef2e Update README.md to include npm as option for installing. (#523)
* add npm as option for installing

* Update README.md
2017-10-27 12:12:54 -06:00
Abu ShamsutdinovandTanner Linsley 2b9c546132 Added a comma into an array (#524) 2017-10-27 12:12:02 -06:00
Jon TanseyandTanner Linsley 55ef8a9e7d Fix missing comma in Component Overrides docs (#525) 2017-10-27 12:11:46 -06:00
simon-bondandTanner Linsley 189ee436f9 Supply sort direction to custom sort methods (#476) (#533) 2017-10-27 12:11:34 -06:00
SudhanshuandTanner Linsley 225a74770b Update index.styl (#537) 2017-10-27 12:11:09 -06:00
Will OlsonandTanner Linsley fa425a162a Linter cleanup (#548)
* chore: Add local dependencies needed to run the test suite

* style: Fix eslint errors regarding multilines JSX
2017-10-27 12:10:41 -06:00
Will OlsonandTanner Linsley e42b7bbd7d Add the PropTypes node module (#550)
* feat: Add prop types to the library

* fix: Update typos in src/propTypes.js
2017-10-27 12:08:33 -06:00
Erkam UyanikandTanner Linsley 9efee144a8 Update README.md (#551)
Correct a typo
2017-10-27 12:07:47 -06:00
Mike DeVitaandTanner Linsley 56b721c185 fixes issue #564 - IE not displaying rows (#569) 2017-10-27 12:07:29 -06:00
Dylan MarkowandTanner Linsley e91bb91ea1 Expose page/pageSize to rows/cells (#581) 2017-10-27 12:06:46 -06:00
Tanner Linsley dadfcc121c 6.6.0 2017-09-29 12:06:18 -06:00
Eric BerryandTanner Linsley 8cec156d13 Re-position code sponsor (#504)
We have found that with longer documentation files, the position of the sponsor link is more effective in helping fund the project when it's higher in the readme.
2017-09-21 07:39:24 -06:00
Eric BerryandTanner Linsley 5c531095a9 Update Code Sponsor link position (#480)
When the link is found at the bottom of the README, it is more effective in helping funding this project.
2017-09-07 20:43:48 -06:00
Tanner LinsleyandGitHub 8d4deb3496 Update README.md
Fixes #475
2017-09-01 16:05:33 -06:00
Tanner LinsleyandGitHub 646b701f93 Update package.json
Fixes #464
2017-08-31 17:33:10 -06:00
Colwyn Fritze-MoorandTanner Linsley 3043cbe4b4 readme-updated: Fixed incorrect property names for expanded (was expandedRows) and resized (was resizing). (#432) 2017-08-31 17:30:28 -06:00
Peter BellandTanner Linsley fcb82694bb Fixed documentation: was referencing expandedRows props for ReactTable, but it was renamed to expanded (#440) 2017-08-31 17:29:53 -06:00
SudhanshuandTanner Linsley e8c557d70e Make the css for input and select more specific (#446)
The current css selectors, eg. `.ReactTable input` cause conflicts with `input` elements inside Cells. So changed it to `.ReactTable .-pagination input`.
2017-08-31 17:24:21 -06:00
Conrad PankoffandTanner Linsley ff95c21440 make rt-tfoot flex behaviour the same as rt-thead (#459)
This brings `rt-tfoot` into line with `rt-thead` in terms of flex behaviour.
Without this, it's possible for an `rt-tr` to be taller than its containing
`rt-tfoot` without causing it to expand, which causes the outer `rt-table` to
scroll vertically.
2017-08-31 17:23:44 -06:00
RimšelisandTanner Linsley 2630161222 fixed README's Fully Controlled Component filtered (#456) 2017-08-25 10:53:07 -06:00
Tanner LinsleyandGitHub e67072edae Update README.md 2017-08-23 11:43:51 -06:00
Tanner LinsleyandGitHub fb569ad592 Update README.md 2017-08-23 11:43:19 -06:00
Tanner LinsleyandGitHub b957503612 Update ISSUE_TEMPLATE.md 2017-08-09 16:18:29 -06:00
Tanner LinsleyandGitHub 3d9b7b1186 Update README.md 2017-08-09 16:11:11 -06:00
Jeffrey PriebeandTanner Linsley e3528fef38 Use isResizable value in ThComponent classname (#429)
Also in child div
2017-08-09 12:55:43 -06:00
Tanner Linsley 6b192bd363 More responsiveness on css examples 2017-08-03 19:55:22 -06:00
Tanner Linsley 0725f2159d Move Doc Examples to CodeSandbox.io 2017-08-03 19:53:42 -06:00
Tanner Linsley 5d2deda246 Transfer repo to react-tools 2017-08-02 16:05:17 -06:00
Tanner Linsley 2961eb8a18 Updated Logo 2017-08-02 16:05:17 -06:00
Tanner Linsley d170adb6a7 Create CNAME 2017-08-02 15:57:20 -06:00
Tanner Linsley d8aec06496 6.5.3 2017-08-02 13:39:42 -06:00
Tanner Linsley 8efeef3b8b Fix onClick proxying and eslint 2017-08-02 13:39:34 -06:00
Tanner Linsley 8004e7a85f 6.5.2 2017-08-02 13:25:44 -06:00
Tanner Linsley 84af88916a Fix Typo 2017-08-02 13:16:54 -06:00
Tanner Linsley 9846bf1905 Provide onClick handleOriginal function
Fixes #406
2017-08-02 13:15:16 -06:00
Tanner Linsley bf88dda5dc Revert to page 1 on filter change
Fixes #273
2017-08-02 12:36:49 -06:00
Tanner Linsley 7f5779a833 Some simple event propagation fixes (but not the 100% fix) 2017-08-02 12:10:46 -06:00
Tanner Linsley 8792bd95a0 Move onFetchData for better timing and reliability
Fixes #294
2017-08-02 08:59:54 -06:00
ldsteinandTanner Linsley 098b1fec51 Max width NaN fix (#415)
* Added button to reset table state in Controlled Component story

* Fix maxWidth style when value is NaN

* code formatting
2017-08-01 21:27:40 -06:00
Tanner Linsley 750cfe3ac4 Fix Linting 2017-07-31 10:37:12 -06:00
Tanner Linsley 370f443347 Fix pivot header groups
Fixes #376
2017-07-31 10:29:41 -06:00
Tanner Linsley 67f8c9adf1 Cleanup 2017-07-31 09:36:29 -06:00
Tanner Linsley 867cc25899 Fixed display of inputs and checkboxes
Fixes #398
2017-07-31 09:27:03 -06:00
Caroline ShawandTanner Linsley 639630946c Update README to reflect updates (#400) 2017-07-25 14:01:17 -06:00
qmorelandTanner Linsley 688afd2947 [refs #321]: correct makePathArray function in utils (#326) 2017-07-19 14:43:32 -06:00
Tanner LinsleyandGitHub bbebf02a55 Update README.md 2017-07-17 15:01:04 -06:00
Tanner LinsleyandGitHub f4d3c2d7bb Update README.md 2017-07-17 15:00:31 -06:00
Tanner LinsleyandGitHub f8634e771e Update README.md 2017-07-11 14:32:10 -06:00
emyarodandTanner Linsley ba74ab3ce8 Fix typo (#380) 2017-07-08 10:22:24 -06:00
Tanner Linsley 30ed0c82fc 6.5.1 2017-07-05 17:09:11 -06:00
Tanner Linsley 62f19aecf0 Fix: makeTemplateComponent now supports displayName
Fixes #289
2017-07-05 17:08:08 -06:00
Tanner Linsley 8dc4caff45 Fix: column.getProps().rest props are now applied correctly 2017-07-05 16:58:14 -06:00
Tanner Linsley c2e935d75b Fix: defaultExpanded now works correctly
Fixes #372
2017-07-05 16:58:00 -06:00
Tanner Linsley f9a1cfae1e 6.5.0 2017-07-05 10:31:56 -06:00
Tanner Linsley 5ac2c1779d Feature: column.filterAll + docs 2017-07-05 10:31:50 -06:00
Tanner Linsley 3b2432f535 Formatting with prettier + eslint 2017-07-03 09:48:24 -06:00
Jacob CofmanandTanner Linsley 7aa98887ef fix for issue #240 (#363) 2017-07-03 09:14:45 -06:00
Aaron SchwartzandTanner Linsley d26d82ecfb Fix source code in FixedHeader example (#369) 2017-07-03 09:13:15 -06:00
Tanner Linsley b76f9c956d 6.4.0 2017-06-19 11:34:29 -06:00
Tanner Linsley 2e3743b75f Feature: PadRowComponent prop 2017-06-19 11:34:21 -06:00
Tanner Linsley fdb3e77b00 6.3.0 2017-06-09 21:02:37 -06:00
Tanner Linsley d9248cef2b Added defaultSortDesc prop and formatted with prettier + project's eslint 2017-06-09 21:02:28 -06:00
82 changed files with 23485 additions and 5746 deletions
+1 -72
View File
@@ -1,74 +1,3 @@
module.exports = {
parserOptions: {
ecmaVersion: 8,
ecmaFeatures: {
experimentalObjectRestSpread: true,
jsx: true,
node: false
},
sourceType: 'module'
},
extends: ['standard'],
plugins: ['react'],
rules: {
// Nozzle
'jsx-quotes': [2, 'prefer-single'],
'comma-dangle': [2, 'always-multiline'],
// // React
'react/jsx-boolean-value': 2,
'react/jsx-curly-spacing': [2, 'never'],
'react/jsx-equals-spacing': [2, 'never'],
// 'react/jsx-indent': 2,
'react/jsx-indent-props': [2, 2],
'react/jsx-no-duplicate-props': 2,
'react/jsx-no-undef': 2,
'react/jsx-tag-spacing': [
2,
{
closingSlash: 'never',
beforeSelfClosing: 'always',
afterOpening: 'never'
}
],
'react/jsx-uses-react': 2,
'react/jsx-uses-vars': 2,
'react/self-closing-comp': 2,
'react/jsx-no-bind': [
2,
{
allowArrowFunctions: true,
allowBind: false,
ignoreRefs: true
}
],
'react/no-did-update-set-state': 2,
'react/no-unknown-property': 2,
'react/react-in-jsx-scope': 2,
'react/jsx-closing-bracket-location': [2, 'tag-aligned'],
'react/jsx-tag-spacing': [2, { beforeSelfClosing: 'always' }],
'react/jsx-wrap-multilines': 2,
'react/self-closing-comp': 2,
'react/jsx-key': 2,
'react/jsx-no-comment-textnodes': 2,
'react/jsx-no-duplicate-props': 2,
'react/jsx-no-target-blank': 2,
'react/jsx-no-undef': 2,
'react/jsx-uses-react': 2,
'react/jsx-uses-vars': 2,
'react/no-danger-with-children': 2,
'react/no-deprecated': 2,
'react/no-direct-mutation-state': 2,
'react/no-find-dom-node': 2,
'react/no-is-mounted': 2,
'react/no-render-return-value': 2,
'react/no-string-refs': 2,
'react/no-unknown-property': 2,
'react/react-in-jsx-scope': 2,
'react/require-render-return': 2
// 'react/jsx-max-props-per-line': [2, { maximum: 1 }]
}
extends: 'react-tools',
}
+1
View File
@@ -0,0 +1 @@
* text=auto
+38
View File
@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Codesandbox!**
Use a new [react-table codesandbox](codesandbox.io/s/X6npLXPRW) to reproduce the issue.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
+17
View File
@@ -0,0 +1,17 @@
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,11 @@
---
name: Questions, Support & Help
about: Looking for help? Need a question answered?
---
STOP!!!
Github issues is no place for general support. We encourage you to use our public support forum at https://spectrum.chat/react-table.
NOTE: If a support/help/question issue is opened, it will be closed immediately and be redirected to the forum. Thanks for helping us keep our issues clean and productive!
+3
View File
@@ -1,8 +1,11 @@
node_modules/
lib/
es/
docs/build
react-table.js
react-table.min.js
react-table.css
*.log
.idea
.DS_Store
.history
+167 -38
View File
@@ -1,44 +1,173 @@
## 6.8.6
#### Fixes & Optimizations
* Since `resolveData` is now capable of materializing data on it's own, the `data` prop is no longer required as a prop-type.
## 6.8.4
#### Fixes & Optimizations
* Only run `resolveData` prop when `data` prop has changed, not any others.
## 6.8.3
#### Fixes & Optimizations
* Allow the `resolveData` prop to alter or materialize new data when the `data` prop changes.
## 6.8.1
#### Fixes & Optimizations
* Updated eslint and code formatting
## 6.7.5
#### Fixes & Optimizations
* Now passes `column` to `getResizerProps` (#667)
* NOTE: `getResizerProps` is now only called if the column is resizable
* Fixes the `className` ordering in defaultProps for ThComponent (#673)
* NOTE: user supplied classNames now come at the end so they can extend the defaults
## 6.7.4
#### Fixes & Optimizations
* Fix Prop types for columns
## 6.7.3
#### Fixes & Optimizations
* Fix the rest of the proptypes
## 6.7.2
#### Fixes & Optimizations
* `getPropTypes` proptype check
## 6.7.1
#### Fixes & Optimizations
* `eslint-config` moved to dev deps
## 6.7.0
## 6.7.0-alpha-0
#### New Features
* Expose page/pageSize to rows/cells
* Supply sort direction to custom sort methods
#### Fixes & Optimizations
* README updates
* Linter cleanup
* Added PropTypes node module
* Deps, linting and style upgrades
## 6.6.0
#### Fixes & Optimizations
* moved repo to react-tools
* Doc examples moved to codesandbox.io
* README updates
* CSS refacting for rt-tfoot to match rt-thead
* CSS more specific for input and select
## 6.5.3
#### Fixes & Optimizations
* `onClick` proxying and eslint
## 6.5.2
#### New Features
* Provide onClick handleOriginal function - #406
#### Fixes & Optimizations
* README updates
* `makePathArray` in utils - #326
* Various fixes: #294, #376, #398, #415,
## 6.5.1
#### Fixes & Optimizations
* `defaultExpanded` now works correctly - #372
* `column.getProps().rest` props are now applied correctly
* `makeTemplateComponent` now supports `displayName` - #289
## 6.5.0
##### New Features
* `column.filterAll` - defaults to `false`, but when set to `true` will provide the entire array of rows to `filterMethod` as opposed to one row at a time. This allows for more fine-grained filtering using any method you can dream up. See the [Custom Filtering example](https://react-table.js.org/#/story/custom-filtering) for more info.
## 6.4.0
##### New Features
* `PadRowComponent` - the content rendered inside of a padding row. Defaults to a react component that renders `&nbsp;`
## 6.3.0
##### New Features
* `defaultSortDesc` - allows you to set the default sorting direction for all columns to descending.
* `column.defaultSortDesc` - allows you to set the default sorting direction for a specific column. Falls back to the global `defaultSortDesc` when not set at all.
## 6.0.0
##### New Features
- New Renderers:
- `Aggregated` - Custom renderer for aggregated cells
- `Pivot` - Custom renderer for Pivoted Cells (utilizes `Expander` and `PivotValue`)
- `PivotValue` - Custom renderer for Pivot cell values (deprecates the undocumented `pivotRender` option)
- `Expander` - Custom renderer for Pivot cell Expander
- Added custom sorting methods per table via `defaultSortMethod` and per column via `column.sortMethod`
- Pivot columns are now visibly separate and sorted/filtered independently.
- Added `column.resizable` to override global table `resizable` option for specific columns.
- Added `column.sortable` to override global table `sortable` option for specific columns.
- Added `column.filterable` to override global table `filterable` option for specific columns.
- Added `defaultExpanded` table option.
- All callbacks can now be utilized without needing to hoist and manage the piece of state they export. That is what their prop counterparts are for, so now the corresponding prop is used instead of the callback to detect a "fully controlled" state.
- Prevent transitions while column resizing for a smoother resize effect.
- Disable text selection while resizing columns.
* New Renderers:
* `Aggregated` - Custom renderer for aggregated cells
* `Pivot` - Custom renderer for Pivoted Cells (utilizes `Expander` and `PivotValue`)
* `PivotValue` - Custom renderer for Pivot cell values (deprecates the undocumented `pivotRender` option)
* `Expander` - Custom renderer for Pivot cell Expander
* Added custom sorting methods per table via `defaultSortMethod` and per column via `column.sortMethod`
* Pivot columns are now visibly separate and sorted/filtered independently.
* Added `column.resizable` to override global table `resizable` option for specific columns.
* Added `column.sortable` to override global table `sortable` option for specific columns.
* Added `column.filterable` to override global table `filterable` option for specific columns.
* Added `defaultExpanded` table option.
* All callbacks can now be utilized without needing to hoist and manage the piece of state they export. That is what their prop counterparts are for, so now the corresponding prop is used instead of the callback to detect a "fully controlled" state.
* Prevent transitions while column resizing for a smoother resize effect.
* Disable text selection while resizing columns.
##### Breaking API Changes
- New Renderers:
- `Cell` - deprecates and replaces `render`
- `Header` - deprecates and replaces `header`
- `Footer` - deprecates and replaces `footer`
- `Filter`- deprecates and replaces `filterRender`
- Callbacks now provide the destination state as the primary parameter(s). This makes hoisting and controlling the state in redux or component state much easier. eg.
- `onSorting` no longer requires you to build your own toggle logic
- `onResize` no longer requires you to build your own resize logic
- Renamed `onChange` callback -> `onFetchData` which will always fire when a new data model needs to be fetched (or if not using `manual`, when new data is materialized internally).
- Renamed `filtering` -> `filtered`
- Renamed `sorting` -> `sorted`
- Renamed `expandedRows` -> `expanded`
- Renamed `resizing` -> `resized`
- Renamed `defaultResizing` -> `defaultResized`
- Renamed `defaultFiltering` -> `defaultFiltered`
- Renamed `defaultSorting` -> `defaultSorted`
- Renamed `onSortingChange` -> `onSortedChange`
- Renamed `onFilteringChange` -> `onFilteredChange`
- Renamed `onResize` -> `onResizedChange`
- Renamed `onExpandRow` -> `onExpandedChange`
- Renamed `showFilters` -> `filterable`
- Renamed `hideFilter` -> `filterable` (Column option. Note the true/false value is now flipped.)
- `cellInfo.row` and `rowInfo.row` now reference the materialize data for the table. To reference the original row, use `cellInfo.original` and `rowInfo.original`
- Removed `pivotRender` column option. You can now control how the value is displayed by overriding the `PivotValueComponent` or the individual column's `PivotValue` renderer. See [Pivoting Options Story](https://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Pivoting%20Options&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel) for a reference on how to customize pivot column rendering.
* New Renderers:
* `Cell` - deprecates and replaces `render`
* `Header` - deprecates and replaces `header`
* `Footer` - deprecates and replaces `footer`
* `Filter`- deprecates and replaces `filterRender`
* Callbacks now provide the destination state as the primary parameter(s). This makes hoisting and controlling the state in redux or component state much easier. eg.
* `onSorting` no longer requires you to build your own toggle logic
* `onResize` no longer requires you to build your own resize logic
* Renamed `onChange` callback -> `onFetchData` which will always fire when a new data model needs to be fetched (or if not using `manual`, when new data is materialized internally).
* Renamed `filtering` -> `filtered`
* Renamed `sorting` -> `sorted`
* Renamed `expandedRows` -> `expanded`
* Renamed `resizing` -> `resized`
* Renamed `defaultResizing` -> `defaultResized`
* Renamed `defaultFiltering` -> `defaultFiltered`
* Renamed `defaultSorting` -> `defaultSorted`
* Renamed `onSortingChange` -> `onSortedChange`
* Renamed `onFilteringChange` -> `onFilteredChange`
* Renamed `onResize` -> `onResizedChange`
* Renamed `onExpandRow` -> `onExpandedChange`
* Renamed `showFilters` -> `filterable`
* Renamed `hideFilter` -> `filterable` (Column option. Note the true/false value is now flipped.)
* `cellInfo.row` and `rowInfo.row` now reference the materialize data for the table. To reference the original row, use `cellInfo.original` and `rowInfo.original`
* Removed `pivotRender` column option. You can now control how the value is displayed by overriding the `PivotValueComponent` or the individual column's `PivotValue` renderer. See [Pivoting Options Story](https://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Pivoting%20Options&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel) for a reference on how to customize pivot column rendering.
-15
View File
@@ -1,15 +0,0 @@
## Problem Description
include a detailed explanation of the problem here...
## Code Snippet(s) or Codepen (http://codepen.io/tannerlinsley/pen/QpeZBa?editors=0010)
## Steps to Reproduce
1. list the steps
2. to reproduce the issue
## System Information
* **Browser & Browser Version:**
* **Node Version:**
* **OS Version:**
* **NPM Version:**
* **Yarn Version:**
+338 -172
View File
@@ -1,25 +1,22 @@
<div align="center">
<a href="https://github.com/tannerlinsley/react-table" target="\_parent"><img src="https://github.com/tannerlinsley/react-table/raw/master/media/Banner.png" alt="React Table Logo" style="width:450px;"/></a>
<br />
<br />
<div style="text-align:center;">
<a href="https://github.com/react-tools/react-table" target="\_parent"><img src="https://github.com/react-tools/media/raw/master/logo-react-table.png" alt="React Table Logo" style="width:450px;"/></a>
</div>
# React Table
`react-table` is a **lightweight, fast and extendable datagrid** built for React
<a href="https://travis-ci.org/tannerlinsley/react-table" target="\_parent">
<img alt="" src="https://travis-ci.org/tannerlinsley/react-table.svg?branch=master" />
<a href="https://travis-ci.org/react-tools/react-table" target="\_parent">
<img alt="" src="https://travis-ci.org/react-tools/react-table.svg?branch=master" />
</a>
<a href="https://npmjs.com/package/react-table" target="\_parent">
<img alt="" src="https://img.shields.io/npm/dm/react-table.svg" />
</a>
<a href="https://react-chat-signup.herokuapp.com/" target="\_parent">
<img alt="" src="https://img.shields.io/badge/slack-react--chat-blue.svg" />
<a href="https://spectrum.chat/react-table">
<img alt="Join the community on Spectrum" src="https://withspectrum.github.io/badge/badge.svg" />
</a>
<a href="https://github.com/tannerlinsley/react-table" target="\_parent">
<img alt="" src="https://img.shields.io/github/stars/tannerlinsley/react-table.svg?style=social&label=Star" />
<a href="https://github.com/react-tools/react-table" target="\_parent">
<img alt="" src="https://img.shields.io/github/stars/react-tools/react-table.svg?style=social&label=Star" />
</a>
<a href="https://twitter.com/tannerlinsley" target="\_parent">
<img alt="" src="https://img.shields.io/twitter/follow/tannerlinsley.svg?style=social&label=Follow" />
@@ -28,27 +25,49 @@
<img alt="" src="https://img.shields.io/badge/%24-Donate-brightgreen.svg" />
</a>
## Versions
This document refers to version 6.x.x of react-table.
Previous versions:
[5.x.x Readme](https://github.com/tannerlinsley/react-table/blob/ad7d31cd3978eb45da7c6194dbab93c1e9a8594d/README.md)
<br />
<br />
## Features
- Lightweight at 7kb (and just 2kb more for styles)
- Fully customizable JSX templating
- Supports both Client-side & Server-side pagination and multi-sorting
- Column Pivoting & Aggregation
- Lightweight at 11kb (and just 2kb more for styles)
- Fully customizable (JSX, templates, state, styles, callbacks)
- Client-side & Server-side pagination
- Multi-sort
- Filters
- Pivoting & Aggregation
- Minimal design & easily themeable
- Fully controllable via optional props and callbacks
- <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
- <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
## Demos and examples
- <a href="http://codepen.io/tannerlinsley/pen/QpeZBa?editors=0010" target="\_blank">Codepen</a>
- <a href="http://react-table.js.org/#/story/simple-table" target="\_parent">Storybook</a>
## [Demos and examples](http://react-table.js.org/#/story/simple-table)
## Versions
- This documentation is for version 6 of react-table.
- [View the Changelog](https://github.com/react-tools/react-table/blob/master/CHANGELOG.md)
- Previous versions:
- [5.x.x Readme](https://github.com/react-tools/react-table/blob/ad7d31cd3978eb45da7c6194dbab93c1e9a8594d/README.md)
## Sponsors
| | |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [![Platinum Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/platinum.png)](https://patreon.com/tannerlinsley) | [![Retool](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/sponsor-retool.png)](https://tryretool.com/?utm_source=sponsor&utm_campaign=react_table) |
| | | |
| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| [![Gold Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/gold.png)](https://patreon.com/tannerlinsley) | [![Retool](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/gold-placeholder.png)](https://patreon.com/tannerlinsley) | [![Retool](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/gold-placeholder.png)](https://patreon.com/tannerlinsley) |
| | | | |
| ----------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| [![Silver Sponsors](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/silver.png)](https://patreon.com/tannerlinsley) | [![Retool](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/silver-placeholder.png)](https://patreon.com/tannerlinsley) | [![Retool](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/silver-placeholder.png)](https://patreon.com/tannerlinsley) | [![Retool](https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/silver-placeholder.png)](https://patreon.com/tannerlinsley) |
**React Table v7** is mostly planned and I (@tannerlinsley) am looking for Patreon support to make it a reality. It will require a decent time commitment on my part to not only implement it, but also help people migrate and maintain it. If you would like to contribute to my Patreon goal for v7, [visit my Patreon and help me out!](https://patreon.com/tannerlinsley). Gold
## Table of Contents
- [Installation](#installation)
- [Example](#example)
- [Data](#data)
@@ -70,41 +89,56 @@ Previous versions:
- [Scripts](#scripts)
- [Used By](#used-by)
## Installation
1. Install React Table as a dependency
1. Install React Table as a dependency
```bash
# Yarn
$ yarn add react-table
# NPM
$ npm install react-table
```
2. Import the `react-table` module
2. Import the `react-table` module
```javascript
// ES6
import ReactTable from 'react-table'
import ReactTable from "react-table";
// ES5
var ReactTable = require('react-table').default
var ReactTable = require("react-table").default;
```
3. Import styles by including `react-table.css`
3. Import styles by including `react-table.css`
```javascript
// JS (Webpack)
import 'react-table/react-table.css'
// Old-school
<link rel="stylesheet" href="node_modules/react-table/react-table.css">
```
##### CDN
```html
<!-- CSS -->
<link rel="stylesheet" href="https://unpkg.com/react-table@latest/react-table.css">
<!-- CSS -->
<link
rel="stylesheet"
href="https://unpkg.com/react-table@latest/react-table.css"
/>
<!-- JS -->
<script src="https://unpkg.com/react-table@latest/react-table.js"></script>
<!-- JS -->
<script src="https://unpkg.com/react-table@latest/react-table.js"></script>
<script src="https://unpkg.com/react-table@latest/react-table.min.js"></script>
<script>
var ReactTable = window.ReactTable.default
</script>
<script>
var ReactTable = window.ReactTable.default;
</script>
```
## Example
```javascript
import ReactTable from 'react-table'
@@ -136,7 +170,7 @@ render() {
accessor: 'friend.age'
}]
<ReactTable
return <ReactTable
data={data}
columns={columns}
/>
@@ -144,15 +178,33 @@ render() {
```
## Data
Simply pass the `data` prop anything that resembles an array or object. Client-side sorting and pagination are built in, and your table will update gracefully as you change any props. [Server-side data](#server-side-data) is also supported!
```javascript
<ReactTable
data={[...]}
/>
```
**Pro Tip: Using the `resolveData` prop** - Any time the `data` prop value changes (using a `===` comparison), the table will update, but sometimes you need to materialize, alter, or shape this data before it enters the table. To do this, you can use the `resolveData` prop! It recieves the `data` prop as the only parameter and returns the resolved data.
```javascript
<ReactTable
data={myData} // The data prop should be immutable and only change when you want to update the table
resolveData={data => data.map(row => row)} // But you can break immutability here because `resolveData` runs when the `data` prop changes!
/>
```
## Props
These are all of the available props (and their default values) for the main `<ReactTable />` component.
```javascript
{
// General
data: [],
resolveData: data => resolvedData,
loading: false,
showPagination: true,
showPaginationTop: false,
@@ -160,15 +212,18 @@ These are all of the available props (and their default values) for the main `<R
showPageSizeOptions: true,
pageSizeOptions: [5, 10, 20, 25, 50, 100],
defaultPageSize: 20,
minRows: undefined,
minRows: undefined, // controls the minimum number of rows to display - default will be `pageSize`
// NOTE: if you set minRows to 0 then you get rid of empty padding rows BUT your table formatting will also look strange when there are ZERO rows in the table
showPageJump: true,
collapseOnSortingChange: true,
collapseOnPageChange: true,
collapseOnDataChange: true,
freezeWhenExpanded: false,
sortable: true,
multiSort: true,
resizable: true,
filterable: false,
defaultSortDesc: false,
defaultSorted: [],
defaultFiltered: [],
defaultResized: [],
@@ -177,13 +232,13 @@ These are all of the available props (and their default values) for the main `<R
const id = filter.pivotId || filter.id
return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true
},
defaultSortMethod: (a, b) => {
defaultSortMethod: (a, b, desc) => {
// force null and undefined to the bottom
a = (a === null || a === undefined) ? -Infinity : a
b = (b === null || b === undefined) ? -Infinity : b
a = a === null || a === undefined ? '' : a
b = b === null || b === undefined ? '' : b
// force any string values to lowercase
a = a === 'string' ? a.toLowerCase() : a
b = b === 'string' ? b.toLowerCase() : b
a = typeof a === 'string' ? a.toLowerCase() : a
b = typeof b === 'string' ? b.toLowerCase() : b
// Return either 1 or -1 to indicate a sort priority
if (a > b) {
return 1
@@ -191,9 +246,11 @@ These are all of the available props (and their default values) for the main `<R
if (a < b) {
return -1
}
// returning 0, undefined or any falsey value will use subsequent sorts or the index as a tiebreaker
// returning 0, undefined or any falsey value will use subsequent sorts or
// the index as a tiebreaker
return 0
},
PadRowComponent: () => <span>&nbsp;</span>, // the content rendered inside of a padding row
// Controlled State Overrides (see Fully Controlled Component section)
page: undefined,
@@ -256,7 +313,21 @@ These are all of the available props (and their default values) for the main `<R
getNoDataProps: () => ({}),
getResizerProps: () => ({}),
// Custom pagination rendering
renderPageJump: ({ onChange, value, onBlur, onKeyPress, inputType, pageJumpText }) => component,
renderCurrentPage: page => component,
renderTotalPagesCount: pages => component,
renderPageSizeOptions: ({
pageSize,
pageSizeOptions,
rowsSelectorText,
onPageSizeChange,
rowsText,
}) => component
// Global Column Defaults
// To override only some values, import { ReactTableDefaults } from 'react-table'
// and construct your overrides (e.g. {...ReactTableDefaults.column, className: 'react-table-cell'})
column: {
// Renderers
Cell: undefined,
@@ -285,11 +356,15 @@ These are all of the available props (and their default values) for the main `<R
footerClassName: '',
footerStyle: {},
getFooterProps: () => ({}),
filterAll: false,
filterMethod: undefined,
sortMethod: undefined
sortMethod: undefined,
defaultSortDesc: undefined,
},
// Global Expander Column Defaults
// To override only some values, import { ReactTableDefaults } from 'react-table'
// and construct your overrides (e.g. {...ReactTableDefaults.expanderDefaults, sortable: true})
expanderDefaults: {
sortable: false,
resizable: false,
@@ -304,23 +379,27 @@ These are all of the available props (and their default values) for the main `<R
previousText: 'Previous',
nextText: 'Next',
loadingText: 'Loading...',
noDataText: 'No rows found',
noDataText: 'No rows found',
pageText: 'Page',
ofText: 'of',
rowsText: 'rows',
// Accessibility Labels
pageJumpText: 'jump to page',
rowsSelectorText: 'rows per page',
}
```
You can easily override the core defaults like so:
```javascript
import { ReactTableDefaults } from 'react-table'
import { ReactTableDefaults } from "react-table";
Object.assign(ReactTableDefaults, {
defaultPageSize: 10,
minRows: 3,
minRows: 3
// etc...
})
});
```
Or just define them as props
@@ -334,7 +413,8 @@ Or just define them as props
```
## Columns
`<ReactTable/>` requires a `columns` prop, which is an array of objects containing the following properties
`<ReactTable />` requires a `columns` prop, which is an array of objects containing the following properties
```javascript
[{
@@ -349,7 +429,7 @@ Or just define them as props
Aggregated: JSX | String | Function // Used to render aggregated cells. Defaults to a comma separated list of values.
Pivot: JSX | String | Function | cellInfo => ( // Used to render a pivoted cell
<span>
<Expander/><PivotValue /> // By default, will utilize the the PivotValue and Expander components at run time
<Expander /><PivotValue /> // By default, will utilize the the PivotValue and Expander components at run time
</span>
),
PivotValue: JSX | String | Function // Used to render the value inside of a Pivot cell
@@ -394,15 +474,18 @@ Or just define them as props
getFooterProps: (state, rowInfo, column, instance) => ({}), // A function that returns props to decorate the `td` element of the column's footer
// Filtering
filterMethod: (filter, row, column) => {return true}, // A function returning a boolean that specifies the filtering logic for the column
// filter == an object specifying which filter is being applied. Format: {id: [the filter column's id], value: [the value the user typed in the filter field], pivotId: [if filtering on a pivot column, the pivotId will be set to the pivot column's id and the `id` field will be set to the top level pivoting column]}
// row == the row of data supplied to the table
// column == the column that the filter is on
filterMethod: (filter, row || rows, column) => {return true}, // A function returning a boolean that specifies the filtering logic for the column
// 'filter' == an object specifying which filter is being applied. Format: {id: [the filter column's id], value: [the value the user typed in the filter field], pivotId: [if filtering on a pivot column, the pivotId will be set to the pivot column's id and the `id` field will be set to the top level pivoting column]}
// 'row' || 'rows' == the row (or rows, if filterAll is set to true) of data supplied to the table
// 'column' == the column that the filter is on
filterAll: false
}]
```
## Renderers
React Table supports very flexible renderers for just about everything:
- `Cell` - Renders a standard cell
- `Header` - Renders a column header or column group header
- `Footer` - Renders a column footer
@@ -413,18 +496,20 @@ React Table supports very flexible renderers for just about everything:
- `Expander` - Renders the Expander used in both the default `Pivot` renderer and any expander-designated column
Any of these renderers can be one of the following:
- A React Class
- JSX or any rendered react component
- Stateless functional component
- Function that returns any primitive
All of these formats receive the following props:
```javascript
{
// Row-level props
row: Object, // the materialized row of data
original: , // the original row of data
index: '', // the index of the row in the original arra
index: '', // the index of the row in the original array
viewIndex: '', // the index of the row relative to the current view
level: '', // the nesting level of this row
nestingPath: '', // the nesting path of this row
@@ -447,6 +532,7 @@ All of these formats receive the following props:
```
## Accessors
Accessors are functions that return the value to populate the row's value for the column.
This lets the render function not have to worry about accessing the correct data, the value is automatically populated in it's props.
@@ -456,21 +542,22 @@ Any values that contain a dot (`.`) will be split.
Any values that contain bracket (`[]`) will be split.
This array is then used as the path to the value to return.
("$" is the placeholder value that would be returned by the default accessor)
("\$" is the placeholder value that would be returned by the default accessor)
| value | path | data |
|--------------|-----------------|------------------------|
| "a" | ["a"] | {"a": $} |
| "a.b" | ["a", "b"] | {"a": {"b": $}} |
| "a[0]" | ["a", "0"] | {"a": [$]} |
| ["a.b", "c"] | ["a", "b", "c"] | {"a": {"b": {"c": $}}} |
| value | path | data |
| ------------ | --------------- | ----------------------- |
| "a" | ["a"] | {"a": \$} |
| "a.b" | ["a", "b"] | {"a": {"b": \$}} |
| "a[0]" | ["a", "0"] | {"a": [$]} |
| ["a.b", "c"] | ["a", "b", "c"] | {"a": {"b": {"c": \$}}} |
*NOTE*
_NOTE_
If your data has a field/key with a dot (`.`) you will need to supply a custom accessor.
## Column Header Groups
To group columns with another header column, just nest your columns in a header column. Header columns utilize the same header properties as regular columns.
To group columns with another header column, just nest your columns in a header column. Header columns utilize the same header properties as regular columns.
```javascript
const columns = [{
Header: 'Favorites',
@@ -481,7 +568,7 @@ const columns = [{
}, {
Header: 'Food',
accessor: 'favorites.food'
} {
}, {
Header: 'Actor',
accessor: 'favorites.actor'
}]
@@ -489,9 +576,11 @@ const columns = [{
```
## Custom Cell, Header and Footer Rendering
You can use any react component or JSX to display content in column headers, cells and footers. Any component you use will be passed the following props (if available):
- `row` - Original row from your data
- `row` - The post-accessed values from the original row
- `original` - The post-accessed values from the original row
- `index` - The index of the row
- `viewIndex` - the index of the row relative to the current page
- `level` - The nesting depth (zero-indexed)
@@ -502,53 +591,68 @@ You can use any react component or JSX to display content in column headers, cel
```javascript
// This column uses a stateless component to produce a different colored bar depending on the value
// You can also use stateful components or any other function that returns JSX
const columns = [{
Header: () => <span><i className='fa-tasks' /> Progress</span>,
accessor: 'progress',
Cell: row => (
<div
style={{
width: '100%',
height: '100%',
backgroundColor: '#dadada',
borderRadius: '2px'
}}
>
const columns = [
{
Header: () => (
<span>
<i className="fa-tasks" /> Progress
</span>
),
accessor: "progress",
Cell: row => (
<div
style={{
width: `${row.value}%`,
height: '100%',
backgroundColor: row.value > 66 ? '#85cc00'
: row.value > 33 ? '#ffbf00'
: '#ff2e00',
borderRadius: '2px',
transition: 'all .2s ease-out'
width: "100%",
height: "100%",
backgroundColor: "#dadada",
borderRadius: "2px"
}}
/>
</div>
)
}]
>
<div
style={{
width: `${row.value}%`,
height: "100%",
backgroundColor:
row.value > 66
? "#85cc00"
: row.value > 33
? "#ffbf00"
: "#ff2e00",
borderRadius: "2px",
transition: "all .2s ease-out"
}}
/>
</div>
)
}
];
```
## Styles
- React-table ships with a minimal and clean stylesheet to get you on your feet quickly.
- The stylesheet is located at `react-table/react-table.css`.
- There are countless ways to import a stylesheet. If you have questions on how to do so, consult the documentation of your build system.
#### Classes
- Adding a `-striped` className to ReactTable will slightly color odd numbered rows for legibility
- Adding a `-highlight` className to ReactTable will highlight any row as you hover over it
#### CSS
We think the default styles looks great! But, if you prefer a more custom look, all of the included styles are easily overridable. Every single component contains a unique class that makes it super easy to customize. Just go for it!
#### JS Styles
Every single react-table element and `get[ComponentName]Props` callback supports `classname` and `style` props.
## Custom Props
#### Built-in Components
Every single built-in component's props can be dynamically extended using any one of these prop-callbacks:
```javascript
<ReactTable
getProps={fn}
@@ -559,6 +663,9 @@ Every single built-in component's props can be dynamically extended using any on
getTheadProps={fn}
getTheadTrProps={fn}
getTheadThProps={fn}
getTheadFilterProps={fn}
getTheadFilterTrProps={fn}
getTheadFilterThProps={fn}
getTbodyProps={fn}
getTrGroupProps={fn}
getTrProps={fn}
@@ -571,48 +678,64 @@ Every single built-in component's props can be dynamically extended using any on
/>
```
If used, **a callback prop must return an valid object**, even if it's an empty one.
These callbacks are executed with each render of the element with four parameters:
1. Table State
2. RowInfo (undefined if not applicable)
3. Column (undefined if not applicable)
4. React Table Instance
1. Table State
2. RowInfo (undefined if not applicable)
3. Column (undefined if not applicable)
4. React Table Instance
This makes it extremely easy to add, say... a row click callback!
```javascript
// When any Td element is clicked, we'll log out some information
<ReactTable
getTdProps={(state, rowInfo, column, instance) => {
return {
onClick: e => {
console.log('A Td Element was clicked!')
console.log('it produced this event:', e)
console.log('It was in this column:', column)
console.log('It was in this row:', rowInfo)
console.log('It was in this table instance:', instance)
onClick: (e, handleOriginal) => {
console.log("A Td Element was clicked!");
console.log("it produced this event:", e);
console.log("It was in this column:", column);
console.log("It was in this row:", rowInfo);
console.log("It was in this table instance:", instance);
// IMPORTANT! React-Table uses onClick internally to trigger
// events like expanding SubComponents and pivots.
// By default a custom 'onClick' handler will override this functionality.
// If you want to fire the original onClick handler, call the
// 'handleOriginal' function.
if (handleOriginal) {
handleOriginal();
}
}
}
};
}}
/>
```
You can use these callbacks for dynamic styling as well!
```javascript
// Any Tr element will be green if its (row.age > 20)
<ReactTable
getTrProps={(state, rowInfo, column) => {
return {
style: {
background: rowInfo.row.age > 20 ? 'green' : 'red'
background: rowInfo.row.age > 20 ? "green" : "red"
}
}
};
}}
/>
```
#### Column Components
Just as core components can have dynamic props, columns and column headers can too!
You can utilize either of these prop callbacks on columns:
```javascript
const columns = [{
getHeaderProps: () => (...),
@@ -621,22 +744,27 @@ const columns = [{
```
In a similar fashion these can be used to dynamically style just about anything!
```javascript
// This columns cells will be red if (row.name === Santa Clause)
const columns = [{
getProps: (state, rowInfo, column) => {
return {
style: {
background: rowInfo.row.name === 'Santa Clause' ? 'red' : null
}
const columns = [
{
getProps: (state, rowInfo, column) => {
return {
style: {
background: rowInfo.row.name === "Santa Clause" ? "red" : null
}
};
}
}
}]
];
```
## Pivoting and Aggregation
Pivoting the table will group records together based on their accessed values and allow the rows in that group to be expanded underneath it.
To pivot, pass an array of `columnID`'s to `pivotBy`. Remember, a column's `id` is either the one that you assign it (when using a custom accessors) or its `accessor` string.
```javascript
<ReactTable
...
@@ -645,52 +773,60 @@ To pivot, pass an array of `columnID`'s to `pivotBy`. Remember, a column's `id`
```
Naturally when grouping rows together, you may want to aggregate the rows inside it into the grouped column. No aggregation is done by default, however, it is very simple to aggregate any pivoted columns:
```javascript
// In this example, we use lodash to sum and average the values, but you can use whatever you want to aggregate.
const columns = [{
Header: 'Age',
accessor: 'age',
aggregate: (values, rows) => _.round(_.mean(values)),
Aggregated: row => {
// You can even render the cell differently if it's an aggregated cell
return <span>row.value (avg)</span>
const columns = [
{
Header: "Age",
accessor: "age",
aggregate: (values, rows) => _.round(_.mean(values)),
Aggregated: row => {
// You can even render the cell differently if it's an aggregated cell
return <span>row.value (avg)</span>;
}
},
{
Header: "Visits",
accessor: "visits",
aggregate: (values, rows) => _.sum(values)
}
}, {
Header: 'Visits',
accessor: 'visits',
aggregate: (values, rows) => _.sum(values)
}]
];
```
Pivoted columns can be sorted just like regular columns including holding down the `<shift>` button to multi-sort.
## Sub Tables and Sub Components
By adding a `SubComponent` props, you can easily add an expansion level to all root-level rows:
```javascript
<ReactTable
data={data}
columns={columns}
defaultPageSize={10}
SubComponent={(row) => {
SubComponent={row => {
return (
<div>
You can put any component you want here, even another React Table! You even have access to the row-level data if you need! Spark-charts, drill-throughs, infographics... the possibilities are endless!
You can put any component you want here, even another React Table! You
even have access to the row-level data if you need! Spark-charts,
drill-throughs, infographics... the possibilities are endless!
</div>
)
);
}}
/>
```
## Server-side Data
If you want to handle pagination, sorting, and filtering on the server, `react-table` makes it easy on you.
1. Feed React Table `data` from somewhere dynamic. eg. `state`, a redux store, etc...
1. Add `manual` as a prop. This informs React Table that you'll be handling sorting and pagination server-side
1. Subscribe to the `onFetchData` prop. This function is called at `compomentDidMount` and any time sorting, pagination or filterting is changed in the table
1. In the `onFetchData` callback, request your data using the provided information in the params of the function (current state and instance)
1. Update your data with the rows to be displayed
1. Optionally set how many pages there are total
1. Feed React Table `data` from somewhere dynamic. eg. `state`, a redux store, etc...
1. Add `manual` as a prop. This informs React Table that you'll be handling sorting and pagination server-side
1. Subscribe to the `onFetchData` prop. This function is called at `componentDidMount` and any time sorting, pagination or filterting is changed in the table
1. In the `onFetchData` callback, request your data using the provided information in the params of the function (current state and instance)
1. Update your data with the rows to be displayed
1. Optionally set how many pages there are total
```javascript
<ReactTable
@@ -721,12 +857,14 @@ If you want to handle pagination, sorting, and filtering on the server, `react-t
/>
```
For a detailed example, take a peek at our <a href="https://github.com/tannerlinsley/react-table/blob/master/stories/ServerSide.js" target="\_parent">async table mockup</a>
For a detailed example, take a peek at our <a href="https://react-table.js.org/#/story/server-side-data" target="\_parent">async table mockup</a>
## Fully Controlled Component
React Table by default works fantastically out of the box, but you can achieve even more control and customization if you choose to maintain the state yourself. It is very easy to do, even if you only want to manage *parts* of the state.
React Table by default works fantastically out of the box, but you can achieve even more control and customization if you choose to maintain the state yourself. It is very easy to do, even if you only want to manage _parts_ of the state.
Here are the props and their corresponding callbacks that control the state of the a table:
```javascript
<ReactTable
// Props
@@ -739,7 +877,7 @@ Here are the props and their corresponding callbacks that control the state of t
id: 'firstName',
desc: true
}]}
expandedRows={{ // The nested row indexes on the current page that should appear expanded
expanded={{ // The nested row indexes on the current page that should appear expanded
1: true,
4: true,
5: {
@@ -747,11 +885,11 @@ Here are the props and their corresponding callbacks that control the state of t
3: true
}
}}
filters={[{ // the current filters model
filtered={[{ // the current filters model
id: 'lastName',
value: 'linsley'
}]}
resizing={[{ // the current resized column model
resized={[{ // the current resized column model
"id": "lastName",
"value": 446.25
}]}
@@ -760,43 +898,51 @@ Here are the props and their corresponding callbacks that control the state of t
onPageChange={(pageIndex) => {...}} // Called when the page index is changed by the user
onPageSizeChange={(pageSize, pageIndex) => {...}} // Called when the pageSize is changed by the user. The resolve page is also sent to maintain approximate position in the data
onSortedChange={(newSorted, column, shiftKey) => {...}} // Called when a sortable column header is clicked with the column itself and if the shiftkey was held. If the column is a pivoted column, `column` will be an array of columns
onExpandedChange={(newExpanded, index, event) => {...}} // Called when an expander is clicked. Use this to manage `expandedRows`
onFilteredChange={(column, value) => {...}} // Called when a user enters a value into a filter input field or the value passed to the onFiltersChange handler by the filterRender option.
onExpandedChange={(newExpanded, index, event) => {...}} // Called when an expander is clicked. Use this to manage `expanded`
onFilteredChange={(filtered, column) => {...}} // Called when a user enters a value into a filter input field or the value passed to the onFiltersChange handler by the Filter option.
onResizedChange={(newResized, event) => {...}} // Called when a user clicks on a resizing component (the right edge of a column header)
/>
```
## Functional Rendering
Possibly one of the coolest features of React-Table is its ability to expose internal components and state for custom render logic. The easiest way to do this is to pass a function as the child of `<ReactTable />`.
The function you pass will be called with the following items:
- Fully-resolved state of the table
- A function that returns the standard table component
- The instance of the component
You can then return any JSX or react you want! This turns out to be perfect for:
- Accessing the internal state of the table without a `ref`
- Decorating the table or extending it with your own UI
- Building your own custom display logic
Accessing internal state and wrapping with more UI:
```javascript
<ReactTable
data={data}
columns={columns}
>
<ReactTable data={data} columns={columns}>
{(state, makeTable, instance) => {
return (
<div style={{
background: '#ffcf00',
borderRadius: '5px',
overflow: 'hidden',
padding: '5px'
}}>
<pre><code>state.allVisibleColumns === {JSON.stringify(state.allVisibleColumns, null, 4)}</code></pre>
<div
style={{
background: "#ffcf00",
borderRadius: "5px",
overflow: "hidden",
padding: "5px"
}}
>
<pre>
<code>
state.allVisibleColumns ==={" "}
{JSON.stringify(state.allVisibleColumns, null, 4)}
</code>
</pre>
{makeTable()}
</div>
)
);
}}
</ReactTable>
```
@@ -804,41 +950,55 @@ Accessing internal state and wrapping with more UI:
The possibilities are endless!
## Sorting
Sorting comes built in with React-Table. Click column header to sort by its column. Click it again to reverse the sort.
Sorting comes built in with React-Table.
- Click a column header to sort by its accessor.
- Click it again to reverse the sort.
- Set `defaultSortDesc` property to `true` to make the first sort direction default to descending.
- Override a specific column's default sort direction by using the same `defaultSortDesc` property on a column, set to `true`
## Multi-Sort
When clicking on a column header, hold shift to multi-sort! You can toggle `ascending` `descending` and `none` for multi-sort columns. Clicking on a header without holding shift will clear the multi-sort and replace it with the single sort of that column. It's quite handy!
You can set the `multiSort` prop to `false` to disable this feature (which may be useful for server-side sorting when you are not
going to sort multiple columns).
## Custom Sorting Algorithm
To override the default sorting algorithm for the whole table use the `defaultSortMethod` prop.
To override the sorting algorithm for a single column, use the `sortMethod` column property.
Supply a function that implements the native javascript [`Array.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) interface. This is React Table's default sorting algorithm:
- `a` the first value to compare
- `b` the second value to compare
- `dir` the
- `desc` true if sort is descending, false if ascending
```javascript
defaultSortMethod = (a, b) => {
defaultSortMethod = (a, b, desc) => {
// force null and undefined to the bottom
a = (a === null || a === undefined) ? -Infinity : a
b = (b === null || b === undefined) ? -Infinity : b
a = a === null || a === undefined ? -Infinity : a;
b = b === null || b === undefined ? -Infinity : b;
// force any string values to lowercase
a = typeof a === 'string' ? a.toLowerCase() : a
b = typeof b === 'string' ? b.toLowerCase() : b
a = typeof a === "string" ? a.toLowerCase() : a;
b = typeof b === "string" ? b.toLowerCase() : b;
// Return either 1 or -1 to indicate a sort priority
if (a > b) {
return 1
return 1;
}
if (a < b) {
return -1
return -1;
}
// returning 0 or undefined will use any subsequent column sorting methods or the row index as a tiebreaker
return 0
}
return 0;
};
```
## Filtering
Filtering can be enabled by setting the `filterable` option on the table.
If you don't want particular column to be filtered you can set the `filterable={false}` option on the column.
@@ -847,12 +1007,18 @@ By default the table tries to filter by checking if the row's value starts with
If you want to override a particular column's filtering method, you can set the `filterMethod` option on a column.
To completely override the filter that is shown, you can set the `Filter` column option. Using this option you can specify the JSX that is shown. The option is passed an `onChange` method which must be called with the the value that you wan't to pass to the `filterMethod` option whenever the filter has changed.
By default, `filterMethod` is passed a single row of data at a time, and you are responsible for returning `true` or `false`, indicating whether it should be shown.
Alternatively, you can set `filterAll` to `true`, and `filterMethod` will be passed the entire array of rows to be filtered, and you will then be responsible for returning the new filtered array. This is extremely handy when you need to utilize a utility like fuzzy matching that requires the entire array of items.
To completely override the filter that is shown, you can set the `Filter` column option. Using this option you can specify the JSX that is shown. The option is passed an `onChange` method which must be called with the the value that you want to pass to the `filterMethod` option whenever the filter has changed.
See <a href="http://react-table.js.org/#/story/custom-filtering" target="\_parent">Custom Filtering</a> demo for examples.
## Component Overrides
Though we confidently stand by the markup and architecture behind it, `react-table` does offer the ability to change the core componentry it uses to render everything. You can extend or override these internal components by passing a react component to it's corresponding prop on either the global props or on a one-off basis like so:
```javascript
// Change the global default
import { ReactTableDefaults } from 'react-table'
@@ -862,7 +1028,7 @@ Object.assign(ReactTableDefaults, {
TbodyComponent: component,
TrGroupComponent: component,
TrComponent: component,
ThComponent: component
ThComponent: component,
TdComponent: component,
TfootComponent: component,
ExpanderComponent: component,
@@ -886,10 +1052,10 @@ Object.assign(ReactTableDefaults, {
/>
```
If you choose to change the core components React-Table uses to render, you must make sure your replacement components consume and utilize all of the supplied and inherited props that are needed for that component to function properly. We would suggest investigating <a href="https://github.com/tannerlinsley/react-table/blob/master/src/index.js" target="\_parent">the source</a> for the component you wish to replace.
If you choose to change the core components React-Table uses to render, you must make sure your replacement components consume and utilize all of the supplied and inherited props that are needed for that component to function properly. We would suggest investigating <a href="https://github.com/react-tools/react-table/blob/master/src/index.js" target="\_parent">the source</a> for the component you wish to replace.
## Contributing
To suggest a feature, create an issue if it does not already exist.
If you would like to help develop a suggested feature follow these steps:
@@ -898,7 +1064,7 @@ If you would like to help develop a suggested feature follow these steps:
- Auto-build files as you edit with `$ yarn run watch`
- Implement your changes to files in the `src/` directory
- Run the <a href="https://github.com/tannerlinsley/react-story">React Story</a> locally with `$ yarn run docs`
- View changes as you edit `docs/src`,
- View changes as you edit `docs/src`
- Submit PR for review
#### Scripts
+77
View File
@@ -0,0 +1,77 @@
module.exports = {
parserOptions: {
ecmaVersion: 8,
ecmaFeatures: {
experimentalObjectRestSpread: true,
jsx: true,
node: false,
classes: true
},
sourceType: 'module'
},
parser: 'babel-eslint',
extends: ['standard'],
plugins: ['react'],
rules: {
// Nozzle
'jsx-quotes': [2, 'prefer-single'],
'comma-dangle': [2, 'always-multiline'],
// // React
'react/jsx-boolean-value': 2,
'react/jsx-curly-spacing': [2, 'never'],
'react/jsx-equals-spacing': [2, 'never'],
// 'react/jsx-indent': 2,
'react/jsx-indent-props': [2, 2],
'react/jsx-no-duplicate-props': 2,
'react/jsx-no-undef': 2,
'react/jsx-tag-spacing': [
2,
{
closingSlash: 'never',
beforeSelfClosing: 'always',
afterOpening: 'never'
}
],
'react/jsx-uses-react': 2,
'react/jsx-uses-vars': 2,
'react/self-closing-comp': 2,
'react/jsx-no-bind': [
2,
{
allowArrowFunctions: true,
allowBind: false,
ignoreRefs: true
}
],
'react/no-did-update-set-state': 2,
'react/no-unknown-property': 2,
'react/react-in-jsx-scope': 2,
'react/jsx-closing-bracket-location': [0, 'tag-aligned'],
'react/jsx-tag-spacing': [2, { beforeSelfClosing: 'always' }],
'react/jsx-wrap-multilines': 2,
'react/self-closing-comp': 2,
'react/jsx-key': 2,
'react/jsx-no-comment-textnodes': 2,
'react/jsx-no-duplicate-props': 2,
'react/jsx-no-target-blank': 2,
'react/jsx-no-undef': 2,
'react/jsx-uses-react': 2,
'react/jsx-uses-vars': 2,
'react/no-danger-with-children': 2,
'react/no-deprecated': 2,
'react/no-direct-mutation-state': 2,
'react/no-find-dom-node': 2,
'react/no-is-mounted': 2,
'react/no-render-return-value': 2,
'react/no-string-refs': 2,
'react/no-unknown-property': 2,
'react/react-in-jsx-scope': 2,
'react/require-render-return': 2
// 'react/jsx-max-props-per-line': [2, { maximum: 1 }]
}
}
+1
View File
@@ -0,0 +1 @@
react-table.js.org
+197 -192
View File
@@ -5,83 +5,83 @@ You can find the most recent version of this guide [here](https://github.com/fac
## Table of Contents
- [Updating to New Releases](#updating-to-new-releases)
- [Sending Feedback](#sending-feedback)
- [Folder Structure](#folder-structure)
- [Available Scripts](#available-scripts)
- [npm start](#npm-start)
- [npm test](#npm-test)
- [npm run build](#npm-run-build)
- [npm run eject](#npm-run-eject)
- [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
- [Debugging in the Editor](#debugging-in-the-editor)
- [Changing the Page `<title>`](#changing-the-page-title)
- [Installing a Dependency](#installing-a-dependency)
- [Importing a Component](#importing-a-component)
- [Adding a Stylesheet](#adding-a-stylesheet)
- [Post-Processing CSS](#post-processing-css)
- [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
- [Adding Images and Fonts](#adding-images-and-fonts)
- [Using the `public` Folder](#using-the-public-folder)
- [Changing the HTML](#changing-the-html)
- [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
- [When to Use the `public` Folder](#when-to-use-the-public-folder)
- [Using Global Variables](#using-global-variables)
- [Adding Bootstrap](#adding-bootstrap)
- [Using a Custom Theme](#using-a-custom-theme)
- [Adding Flow](#adding-flow)
- [Adding Custom Environment Variables](#adding-custom-environment-variables)
- [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
- [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
- [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
- [Can I Use Decorators?](#can-i-use-decorators)
- [Integrating with an API Backend](#integrating-with-an-api-backend)
- [Node](#node)
- [Ruby on Rails](#ruby-on-rails)
- [Proxying API Requests in Development](#proxying-api-requests-in-development)
- [Using HTTPS in Development](#using-https-in-development)
- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
- [Running Tests](#running-tests)
- [Filename Conventions](#filename-conventions)
- [Command Line Interface](#command-line-interface)
- [Version Control Integration](#version-control-integration)
- [Writing Tests](#writing-tests)
- [Testing Components](#testing-components)
- [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
- [Initializing Test Environment](#initializing-test-environment)
- [Focusing and Excluding Tests](#focusing-and-excluding-tests)
- [Coverage Reporting](#coverage-reporting)
- [Continuous Integration](#continuous-integration)
- [Disabling jsdom](#disabling-jsdom)
- [Snapshot Testing](#snapshot-testing)
- [Editor Integration](#editor-integration)
- [Developing Components in Isolation](#developing-components-in-isolation)
- [Making a Progressive Web App](#making-a-progressive-web-app)
- [Deployment](#deployment)
- [Static Server](#static-server)
- [Other Solutions](#other-solutions)
- [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
- [Building for Relative Paths](#building-for-relative-paths)
- [Azure](#azure)
- [Firebase](#firebase)
- [GitHub Pages](#github-pages)
- [Heroku](#heroku)
- [Modulus](#modulus)
- [Netlify](#netlify)
- [Now](#now)
- [S3 and CloudFront](#s3-and-cloudfront)
- [Surge](#surge)
- [Advanced Configuration](#advanced-configuration)
- [Troubleshooting](#troubleshooting)
- [`npm start` doesnt detect changes](#npm-start-doesnt-detect-changes)
- [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
- [`npm run build` silently fails](#npm-run-build-silently-fails)
- [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
- [Something Missing?](#something-missing)
* [Updating to New Releases](#updating-to-new-releases)
* [Sending Feedback](#sending-feedback)
* [Folder Structure](#folder-structure)
* [Available Scripts](#available-scripts)
* [npm start](#npm-start)
* [npm test](#npm-test)
* [npm run build](#npm-run-build)
* [npm run eject](#npm-run-eject)
* [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
* [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
* [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
* [Debugging in the Editor](#debugging-in-the-editor)
* [Changing the Page `<title>`](#changing-the-page-title)
* [Installing a Dependency](#installing-a-dependency)
* [Importing a Component](#importing-a-component)
* [Adding a Stylesheet](#adding-a-stylesheet)
* [Post-Processing CSS](#post-processing-css)
* [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
* [Adding Images and Fonts](#adding-images-and-fonts)
* [Using the `public` Folder](#using-the-public-folder)
* [Changing the HTML](#changing-the-html)
* [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
* [When to Use the `public` Folder](#when-to-use-the-public-folder)
* [Using Global Variables](#using-global-variables)
* [Adding Bootstrap](#adding-bootstrap)
* [Using a Custom Theme](#using-a-custom-theme)
* [Adding Flow](#adding-flow)
* [Adding Custom Environment Variables](#adding-custom-environment-variables)
* [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
* [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
* [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
* [Can I Use Decorators?](#can-i-use-decorators)
* [Integrating with an API Backend](#integrating-with-an-api-backend)
* [Node](#node)
* [Ruby on Rails](#ruby-on-rails)
* [Proxying API Requests in Development](#proxying-api-requests-in-development)
* [Using HTTPS in Development](#using-https-in-development)
* [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
* [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
* [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
* [Running Tests](#running-tests)
* [Filename Conventions](#filename-conventions)
* [Command Line Interface](#command-line-interface)
* [Version Control Integration](#version-control-integration)
* [Writing Tests](#writing-tests)
* [Testing Components](#testing-components)
* [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
* [Initializing Test Environment](#initializing-test-environment)
* [Focusing and Excluding Tests](#focusing-and-excluding-tests)
* [Coverage Reporting](#coverage-reporting)
* [Continuous Integration](#continuous-integration)
* [Disabling jsdom](#disabling-jsdom)
* [Snapshot Testing](#snapshot-testing)
* [Editor Integration](#editor-integration)
* [Developing Components in Isolation](#developing-components-in-isolation)
* [Making a Progressive Web App](#making-a-progressive-web-app)
* [Deployment](#deployment)
* [Static Server](#static-server)
* [Other Solutions](#other-solutions)
* [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
* [Building for Relative Paths](#building-for-relative-paths)
* [Azure](#azure)
* [Firebase](#firebase)
* [GitHub Pages](#github-pages)
* [Heroku](#heroku)
* [Modulus](#modulus)
* [Netlify](#netlify)
* [Now](#now)
* [S3 and CloudFront](#s3-and-cloudfront)
* [Surge](#surge)
* [Advanced Configuration](#advanced-configuration)
* [Troubleshooting](#troubleshooting)
* [`npm start` doesnt detect changes](#npm-start-doesnt-detect-changes)
* [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
* [`npm run build` silently fails](#npm-run-build-silently-fails)
* [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
* [Something Missing?](#something-missing)
## Updating to New Releases
@@ -207,7 +207,7 @@ To configure the syntax highlighting in your favorite text editor, head to the [
## Displaying Lint Output in the Editor
>Note: this feature is available with `react-scripts@0.2.0` and higher.
> Note: this feature is available with `react-scripts@0.2.0` and higher.
Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
@@ -215,24 +215,24 @@ They are not required for linting. You should see the linter output right in you
You would need to install an ESLint plugin for your editor first.
>**A note for Atom `linter-eslint` users**
> **A note for Atom `linter-eslint` users**
>If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked:
> If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked:
><img src="http://i.imgur.com/yVNNHJM.png" width="300">
> <img src="http://i.imgur.com/yVNNHJM.png" width="300">
> **For Visual Studio Code users**
>**For Visual Studio Code users**
> VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line:
>VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line:
>```js
{
// ...
"extends": "react-app"
}
```
> ```js
> {
> // ...
> "extends": "react-app"
> }
> ```
````
Then add this block to the `package.json` file of your project:
```js
@@ -242,9 +242,9 @@ Then add this block to the `package.json` file of your project:
"extends": "react-app"
}
}
```
````
Finally, you will need to install some packages *globally*:
Finally, you will need to install some packages _globally_:
```sh
npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@4.0.0 eslint-plugin-flowtype@2.21.0
@@ -265,17 +265,19 @@ Then add the block below to your `launch.json` file and put it inside the `.vsco
```json
{
"version": "0.2.0",
"configurations": [{
"name": "Chrome",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceRoot}/src",
"userDataDir": "${workspaceRoot}/.vscode/chrome",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
"configurations": [
{
"name": "Chrome",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceRoot}/src",
"userDataDir": "${workspaceRoot}/.vscode/chrome",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}
}]
]
}
```
@@ -309,7 +311,7 @@ For example:
### `Button.js`
```js
import React, { Component } from 'react';
import React, { Component } from "react";
class Button extends Component {
render() {
@@ -322,10 +324,9 @@ export default Button; // Dont forget to use export default!
### `DangerButton.js`
```js
import React, { Component } from 'react';
import Button from './Button'; // Import a component from another file
import React, { Component } from "react";
import Button from "./Button"; // Import a component from another file
class DangerButton extends Component {
render() {
@@ -363,8 +364,8 @@ This project setup uses [Webpack](https://webpack.github.io/) for handling all a
### `Button.js`
```js
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles
import React, { Component } from "react";
import "./Button.css"; // Tell Webpack that Button.js uses these styles
class Button extends Component {
render() {
@@ -403,11 +404,11 @@ becomes this:
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-ms-flex-align: center;
align-items: center;
}
```
@@ -436,7 +437,7 @@ Then in `package.json`, add the following lines to `scripts`:
"test": "react-scripts test --env=jsdom",
```
>Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessors documentation.
> Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessors documentation.
Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated.
@@ -477,8 +478,8 @@ You can **`import` an image right in a JavaScript module**. This tells Webpack t
Here is an example:
```js
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
import React from "react";
import logo from "./logo.png"; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
@@ -509,7 +510,7 @@ An alternative way of handling static assets is described in the next section.
## Using the `public` Folder
>Note: this feature is available with `react-scripts@0.5.0` and higher.
> Note: this feature is available with `react-scripts@0.5.0` and higher.
### Changing the HTML
@@ -530,7 +531,7 @@ This mechanism provides a number of benefits:
However there is an **escape hatch** that you can use to add an asset outside of the module system.
If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`.
If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`.
Inside `index.html`, you can use it like this:
@@ -596,19 +597,19 @@ npm install react-bootstrap --save
npm install bootstrap@3 --save
```
Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file:
Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your `src/index.js` file:
```js
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap/dist/css/bootstrap-theme.css";
// Put any other imports below so that CSS from your
// components takes precedence over default styles.
```
Import required React Bootstrap components within ```src/App.js``` file or your custom component files:
Import required React Bootstrap components within `src/App.js` file or your custom component files:
```js
import { Navbar, Jumbotron, Button } from 'react-bootstrap';
import { Navbar, Jumbotron, Button } from "react-bootstrap";
```
Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap.
@@ -632,10 +633,10 @@ Recent versions of [Flow](http://flowtype.org/) work with Create React App proje
To add Flow to a Create React App project, follow these steps:
1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`).
2. Add `"flow": "flow"` to the `scripts` section of your `package.json`.
3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory.
4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`).
1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`).
2. Add `"flow": "flow"` to the `scripts` section of your `package.json`.
3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory.
4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`).
Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors.
You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience.
@@ -645,7 +646,7 @@ To learn more about Flow, check out [its documentation](https://flowtype.org/).
## Adding Custom Environment Variables
>Note: this feature is available with `react-scripts@0.2.3` and higher.
> Note: this feature is available with `react-scripts@0.2.3` and higher.
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By
default you will have `NODE_ENV` defined for you, and any other environment variables starting with
@@ -653,7 +654,7 @@ default you will have `NODE_ENV` defined for you, and any other environment vari
**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it cant possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them.
>Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
> Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
These environment variables will be defined for you on `process.env`. For example, having an environment
variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`.
@@ -699,7 +700,7 @@ a `.env` file. Both of these ways are described in the next few sections.
Having access to the `NODE_ENV` is also useful for performing actions conditionally:
```js
if (process.env.NODE_ENV !== 'production') {
if (process.env.NODE_ENV !== "production") {
analytics.disable();
}
```
@@ -708,7 +709,7 @@ When you compile the app with `npm run build`, the minification step will strip
### Referencing Environment Variables in the HTML
>Note: this feature is available with `react-scripts@0.9.0` and higher.
> Note: this feature is available with `react-scripts@0.9.0` and higher.
You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example:
@@ -742,7 +743,7 @@ REACT_APP_SECRET_CODE=abcdef npm start
### Adding Development Environment Variables In `.env`
>Note: this feature is available with `react-scripts@0.5.0` and higher.
> Note: this feature is available with `react-scripts@0.5.0` and higher.
To define permanent environment variables, create a file called `.env` in the root of your project:
@@ -753,8 +754,8 @@ REACT_APP_SECRET_CODE=abcdef
These variables will act as the defaults if the machine does not explicitly set them.<br>
Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details.
>Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need
these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars).
> Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need
> these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars).
## Can I Use Decorators?
@@ -779,6 +780,7 @@ These tutorials will help you to integrate your app with an API backend running
using `fetch()` to access it.
### Node
Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/).
You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo).
@@ -789,7 +791,7 @@ You can find the companion GitHub repository [here](https://github.com/fullstack
## Proxying API Requests in Development
>Note: this feature is available with `react-scripts@0.2.3` and higher.
> Note: this feature is available with `react-scripts@0.2.3` and higher.
People often serve the front-end React app from the same host and port as their backend implementation.<br>
For example, a production setup might look like this after the app is deployed:
@@ -826,7 +828,7 @@ If the `proxy` option is **not** flexible enough for you, alternatively you can:
## Using HTTPS in Development
>Note: this feature is available with `react-scripts@0.4.0` and higher.
> Note: this feature is available with `react-scripts@0.4.0` and higher.
You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS.
@@ -891,8 +893,7 @@ Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data
## Running Tests
>Note: this feature is available with `react-scripts@0.3.0` and higher.<br>
>[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
> Note: this feature is available with `react-scripts@0.3.0` and higher.<br> >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try.
@@ -937,9 +938,9 @@ To create tests, add `it()` (or `test()`) blocks with the name of the test and i
Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
```js
import sum from './sum';
import sum from "./sum";
it('sums numbers', () => {
it("sums numbers", () => {
expect(sum(1, 2)).toEqual(3);
expect(sum(2, 2)).toEqual(4);
});
@@ -955,12 +956,12 @@ There is a broad spectrum of component testing techniques. They range from a “
Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you havent decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:
```js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
it('renders without crashing', () => {
const div = document.createElement('div');
it("renders without crashing", () => {
const div = document.createElement("div");
ReactDOM.render(<App />, div);
});
```
@@ -976,11 +977,11 @@ npm install --save-dev enzyme react-addons-test-utils
```
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
import React from "react";
import { shallow } from "enzyme";
import App from "./App";
it('renders without crashing', () => {
it("renders without crashing", () => {
shallow(<App />);
});
```
@@ -992,11 +993,11 @@ You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testi
Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
import React from "react";
import { shallow } from "enzyme";
import App from "./App";
it('renders welcome message', () => {
it("renders welcome message", () => {
const wrapper = shallow(<App />);
const welcome = <h2>Welcome to React</h2>;
// expect(wrapper.contains(welcome)).to.equal(true);
@@ -1010,7 +1011,7 @@ Nevertheless you can use a third-party assertion library like [Chai](http://chai
Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written simpler with jest-enzyme.
```js
expect(wrapper).toContainReact(welcome)
expect(wrapper).toContainReact(welcome);
```
To setup jest-enzyme with Create React App, follow the instructions for [initializing your test environment](#initializing-test-environment) to import `jest-enzyme`.
@@ -1021,10 +1022,9 @@ npm install --save-dev jest-enzyme
```js
// src/setupTests.js
import 'jest-enzyme';
import "jest-enzyme";
```
### Using Third Party Assertion Libraries
We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and well fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566).
@@ -1032,28 +1032,29 @@ We recommend that you use `expect()` for assertions and `jest.fn()` for spies. I
However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that youd like to port over, you can import them normally like this:
```js
import sinon from 'sinon';
import { expect } from 'chai';
import sinon from "sinon";
import { expect } from "chai";
```
and then use them in your tests like you normally do.
### Initializing Test Environment
>Note: this feature is available with `react-scripts@0.4.0` and higher.
> Note: this feature is available with `react-scripts@0.4.0` and higher.
If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests.
For example:
#### `src/setupTests.js`
```js
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock
global.localStorage = localStorageMock;
```
### Focusing and Excluding Tests
@@ -1079,10 +1080,12 @@ When creating a build of your application with `npm run build` linter warnings a
Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
### On CI servers
#### Travis CI
1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page.
1. Add a `.travis.yml` file to your git repository.
1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page.
1. Add a `.travis.yml` file to your git repository.
```
language: node_js
node_js:
@@ -1095,10 +1098,12 @@ script:
- npm test
- npm run build
```
1. Trigger your first build with a git push.
1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
1. Trigger your first build with a git push.
1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
### On your own environment
##### Windows (cmd.exe)
```cmd
@@ -1123,7 +1128,7 @@ CI=true npm run build
The test command will force Jest to run tests once instead of launching the watcher.
> If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
> If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
The build command will check for linter warnings and fail if any are found.
@@ -1236,14 +1241,14 @@ You dont necessarily need a static server in order to run a Create React App
Heres a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
```javascript
const express = require('express');
const path = require('path');
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static('./build'));
app.use(express.static("./build"));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, './build', 'index.html'));
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "./build", "index.html"));
});
app.listen(9000);
@@ -1296,7 +1301,7 @@ This will let Create React App correctly infer the root path to use in the gener
#### Serving the Same Build from Different Paths
>Note: this feature is available with `react-scripts@0.9.0` and higher.
> Note: this feature is available with `react-scripts@0.9.0` and higher.
If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`:
@@ -1373,7 +1378,7 @@ For more information see [Add Firebase to your JavaScript Project](https://fireb
### GitHub Pages
>Note: this feature is available with `react-scripts@0.2.0` and higher.
> Note: this feature is available with `react-scripts@0.2.0` and higher.
#### Step 1: Add `homepage` to `package.json`
@@ -1493,9 +1498,9 @@ Choose `build` as the path to deploy.
With this setup Netlify will build and deploy when you push to git or open a pull request:
1. [Start a new netlify project](https://app.netlify.com/signup)
2. Pick your Git hosting service and select your repository
3. Click `Build your site`
1. [Start a new netlify project](https://app.netlify.com/signup)
2. Pick your Git hosting service and select your repository
3. Click `Build your site`
**Support for client-side routing:**
@@ -1511,22 +1516,22 @@ When you build the project, Create React App will place the `public` folder cont
[now](https://zeit.co/now) offers a zero-configuration single-command deployment.
1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
2. Install `serve` by running `npm install --save serve`.
2. Install `serve` by running `npm install --save serve`.
3. Add this line to `scripts` in `package.json`:
3. Add this line to `scripts` in `package.json`:
```
"now-start": "serve build/",
```
4. Run `now` from your project directory. You will see a **now.sh** URL in your output like this:
4. Run `now` from your project directory. You will see a **now.sh** URL in your output like this:
```
> Ready! https://your-project-dirname-tpspyhtdtk.now.sh (copied to clipboard)
```
Paste that URL into your browser when the build is complete, and you will see your deployed app.
Details are available in [this article.](https://zeit.co/blog/now-static)
@@ -1537,7 +1542,7 @@ See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-t
### Surge
Install the Surge CLI if you havent already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account. You just need to specify the *build* folder and your custom domain, and you are done.
Install the Surge CLI if you havent already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account. You just need to specify the _build_ folder and your custom domain, and you are done.
```sh
email: email@domain.com
@@ -1560,14 +1565,14 @@ Note that in order to support routers that use HTML5 `pushState` API, you may wa
You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
Variable | Development | Production | Usage
:--- | :---: | :---: | :---
BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely.
HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host.
PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port.
HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode.
PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.
CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default.
| Variable | Development | Production | Usage |
| :--------- | :--------------------: | :----------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. |
| HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. |
| PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. |
| HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. |
| PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. |
| CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. |
## Troubleshooting
@@ -1607,7 +1612,7 @@ You can find [other installation methods](https://facebook.github.io/watchman/do
If this still doesnt help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
There are also reports that _uninstalling_ Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
### `npm run build` silently fails
+31 -3
View File
@@ -3,10 +3,35 @@
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-scripts": "0.9.5",
"standard": "^10.0.2"
"autoprefixer": "^6.7.0",
"babel-cli": "6.14.0",
"babel-eslint": "6.1.2",
"babel-preset-es2015": "6.14.0",
"babel-preset-react": "6.11.1",
"babel-preset-stage-2": "6.13.0",
"eslint": "^4.1.1",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-class-property": "^1.0.6",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-node": "^5.2.1",
"eslint-plugin-promise": "^3.6.0",
"eslint-plugin-react": "^7.4.0",
"eslint-plugin-standard": "^3.0.1",
"html-element-attributes": "^1.3.0",
"match-sorter": "^1.8.0",
"npm-run-all": "^3.1.1",
"onchange": "^3.0.2",
"postcss-cli": "^2.6.0",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-json-tree": "^0.10.9",
"rimraf": "^2.6.1",
"standard": "^10.0.2",
"stylus": "^0.54.5"
},
"dependencies": {
"eslint-config-react-tools": "^1.0.10",
"github-markdown-css": "^2.6.0",
"marked": "^0.3.6",
"namor": "^1.0.1",
@@ -14,7 +39,10 @@
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-json-tree": "^0.10.9",
"react-story": "^0.0.10"
"react-script": "^2.0.5",
"react-scripts": "^0.9.5",
"react-story": "^0.0.10",
"shortid": "^2.2.8"
},
"scripts": {
"start": "react-scripts start",
File diff suppressed because it is too large Load Diff
+78 -68
View File
@@ -1,32 +1,73 @@
import React from 'react'
/* eslint-disable */
import React from 'react';
//
import ReactStory, { defaultProps } from 'react-story'
import ReactStory, { defaultProps } from 'react-story';
import CodeSandbox from './CodeSandbox.js';
import './stories/utils/prism.css';
import '../../react-table.css';
import './stories/utils/prism.css'
import '../../react-table.css'
import Readme from './stories/Readme.js';
import HOCReadme from './stories/HOCReadme.js';
import Readme from './stories/Readme.js'
import Simple from './stories/Simple.js'
import CellRenderers from './stories/CellRenderers.js'
import DefaultSorting from './stories/DefaultSorting.js'
import CustomSorting from './stories/CustomSorting.js'
import CustomWidths from './stories/CustomWidths.js'
import CustomComponentProps from './stories/CustomComponentProps.js'
import ServerSide from './stories/ServerSide.js'
import SubComponents from './stories/SubComponents.js'
import Pivoting from './stories/Pivoting.js'
import PivotingSubComponents from './stories/PivotingSubComponents.js'
import OneHundredKRows from './stories/OneHundredKRows.js'
import FunctionalRendering from './stories/FunctionalRendering.js'
import CustomExpanderPosition from './stories/CustomExpanderPosition.js'
import NoDataText from './stories/NoDataText.js'
import Footers from './stories/Footers.js'
import Filtering from './stories/Filtering.js'
import ControlledTable from './stories/ControlledTable.js'
import PivotingOptions from './stories/PivotingOptions.js'
import EditableTable from './stories/EditableTable.js'
import FixedHeader from './stories/FixedHeader.js'
import MultiplePagers from './stories/MultiplePagers';
// import Test from './stories/test.js'
// import Tester from './examples/expander';
const stories = [
{ name: 'Readme', component: Readme },
{ name: 'HOC Readme', component: HOCReadme },
// { name: 'Tester', component: Test },
{ name: 'Simple Table', component: CodeSandbox('X6npLXPRW') },
{
name: 'Cell Renderers & Custom Components',
component: CodeSandbox('OyRL04Z4Y')
},
{ name: 'Default Sorting', component: CodeSandbox('gLwmmjzA3') },
{
name: 'Custom Sorting',
component: CodeSandbox('VGx67J35')
},
{ name: 'Custom Column Widths', component: CodeSandbox('o2OORXNXN') },
{ name: 'Custom Component Props', component: CodeSandbox('nZW3L0wp4') },
{ name: 'Server-side Data', component: CodeSandbox('wjrn8wy3R') },
{ name: 'Sub Components', component: CodeSandbox('n2gqAxl7') },
{ name: 'Pivoting & Aggregation', component: CodeSandbox('oNY9z8xN') },
{
name: 'Pivoting & Aggregation w/ Sub Components',
component: CodeSandbox('p0kEVBgQ')
},
{
name: '100k Rows w/ Pivoting & Sub Components',
component: CodeSandbox('DRmKj0XyK')
},
{ name: 'Pivoting Options', component: CodeSandbox('kZKmNBK6r') },
{ name: 'Functional Rendering', component: CodeSandbox('VPZ0Bzv8X') },
{
name: 'Custom Expander Position',
component: CodeSandbox('1jj2XrPEV')
},
{ name: 'Custom "No Data" Text', component: CodeSandbox('RgRpRDv80') },
{ name: 'Footers', component: CodeSandbox('KOqQXn3p8') },
{ name: 'Custom Filtering', component: CodeSandbox('5Eyxxxyx') },
{ name: 'Controlled Component', component: CodeSandbox('r7XEZRK2') },
{ name: 'Editable Table', component: CodeSandbox('n5r19gzQP') },
{
name: 'Fixed Header w/ Vertical Scroll',
component: CodeSandbox('7LY0gjA8O')
},
{
name: 'Multiple Pagers (Top and Bottom)',
component: CodeSandbox('VEZ8OgvX')
},
{ name: 'Tree Table (HOC)', component: CodeSandbox('lxmr4wynzq') },
{ name: 'Select Table (HOC)', component: CodeSandbox('7yq5ylw09j') },
{ name: 'Select Tree Table (HOC)', component: CodeSandbox('2p7jp4klwp') },
{ name: 'Foldable Table (HOC)', component: CodeSandbox('8pkrj5yorl') },
{ name: 'Advanced Expand Table (HOC)', component: CodeSandbox('y2m39jz8v1') }
];
export default class App extends React.Component {
render() {
@@ -41,11 +82,13 @@ export default class App extends React.Component {
StoryWrapper={props => (
<defaultProps.StoryWrapper
css={{
padding: 0
padding: 0,
display: 'flex',
flexDirection: 'column'
}}
>
<a
href="//github.com/tannerlinsley/react-table"
href="//github.com/react-tools/react-table"
style={{
display: 'block',
textAlign: 'center',
@@ -53,58 +96,25 @@ export default class App extends React.Component {
}}
>
<img
src="//npmcdn.com/react-table/media/Banner.png"
src="https://github.com/react-tools/media/raw/master/logo-react-table.png"
alt="React Table Logo"
style={{
width: '100px'
width: '150px',
padding: '10px'
}}
/>
</a>
<div
{...props}
style={{
padding: '10px'
flex: '1 0 auto',
position: 'relative'
}}
/>
</defaultProps.StoryWrapper>
)}
stories={[
{ name: 'Readme', component: Readme },
{ name: 'Simple Table', component: Simple },
{
name: 'Cell Renderers & Custom Components',
component: CellRenderers
},
{ name: 'Default Sorting', component: DefaultSorting },
{ name: 'Custom Sorting', component: CustomSorting },
{ name: 'Custom Column Widths', component: CustomWidths },
{ name: 'Custom Component Props', component: CustomComponentProps },
{ name: 'Server-side Data', component: ServerSide },
{ name: 'Sub Components', component: SubComponents },
{ name: 'Pivoting & Aggregation', component: Pivoting },
{
name: 'Pivoting & Aggregation w/ Sub Components',
component: PivotingSubComponents
},
{
name: '100k Rows w/ Pivoting & Sub Components',
component: OneHundredKRows
},
{ name: 'Pivoting Options', component: PivotingOptions },
{ name: 'Functional Rendering', component: FunctionalRendering },
{
name: 'Custom Expander Position',
component: CustomExpanderPosition
},
{ name: 'Custom "No Data" Text', component: NoDataText },
{ name: 'Footers', component: Footers },
{ name: 'Custom Filtering', component: Filtering },
{ name: 'Controlled Component', component: ControlledTable },
{ name: 'Editable Table', component: EditableTable },
{ name: 'Fixed Header w/ Vertical Scroll', component: FixedHeader },
{ name: 'Multiple Pagers (Top and Bottom)', component: MultiplePagers}
]}
stories={stories}
/>
)
);
}
}
+21
View File
@@ -0,0 +1,21 @@
import React from "react";
export default id => () => {
return (
<iframe
src={`https://codesandbox.io/embed/${id}?autoresize=1&hidenavigation=1&view=${
global.innerWidth < 1000 ? "preview" : "split"
}`}
style={{
position: "absolute",
top: 0,
left: 0,
width: `100%`,
height: `100%`,
border: 0,
overflow: `hidden`
}}
sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
/>
);
};
@@ -0,0 +1,116 @@
import React from 'react';
import { render } from 'react-dom';
import { makeData, Logo, Tips } from './Utils';
import { advancedExpandTableHOC } from '../../../../lib/hoc/advancedExpandTable';
// Import React Table
import ReactTable from 'react-table';
import 'react-table/react-table.css';
const columns = [
{
Header: 'First Name',
accessor: 'firstName',
Cell: props => {
const {
// react table props
columnProps: { rest: { showRowSubComponent } },
nestingPath
} = props;
return (
<div>
<button
onClick={e => showRowSubComponent({ nestingPath: nestingPath }, e)}
>
SHOW SUBCOMPONENT {props.value}
</button>
</div>
);
}
},
{
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
Cell: props => {
const {
// react table props
columnProps: { rest: { toggleRowSubComponent } },
nestingPath
} = props;
return (
<div>
<button
onClick={e =>
toggleRowSubComponent({ nestingPath: nestingPath }, e)
}
>
TOGGLE SUBCOMPONENT {props.value}
</button>
</div>
);
}
},
{
Header: 'Status',
accessor: 'status'
}
]
},
{
Header: 'Stats',
columns: [
{
Header: 'Visits',
accessor: 'visits'
}
]
}
];
const AdvancedExpandReactTable = advancedExpandTableHOC(ReactTable);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: makeData()
};
}
render() {
const { data } = this.state;
return (
<div>
<AdvancedExpandReactTable
data={data}
columns={columns}
defaultPageSize={10}
className='-striped -highlight'
SubComponent={({ row, nestingPath, toggleRowSubComponent }) => {
return (
<div style={{ padding: '20px' }}>
<button
onClick={e => toggleRowSubComponent({ nestingPath }, e)}
>
CLOSE SUBCOMPONENT {row.firstName} {row.lastName}
</button>
</div>
);
}}
/>
<br />
<Tips />
<Logo />
</div>
);
}
}
render(<App />, document.getElementById('root'));
+94
View File
@@ -0,0 +1,94 @@
import React from "react";
export default Component => {
const wrapper = class RTCheckboxTable extends React.Component {
// we only need a Component so we can get the 'ref' - pure components can't get a 'ref'
rowSelector = row => {
if (!row || !row.hasOwnProperty(this.props.keyField)) return null;
const checked = this.props.isSelected(row[this.props.keyField]);
return (
<input
type="checkbox"
checked={checked}
onClick={e => {
const { shiftKey } = e;
e.stopPropagation();
this.props.toggleSelection(row[this.props.keyField], shiftKey, row);
}}
onChange={() => {}}
value=""
/>
);
};
headSelector = row => {
const checked = this.props.selectAll;
return (
<input
type="checkbox"
checked={checked}
onClick={e => {
e.stopPropagation();
this.props.toggleAll();
}}
onChange={() => {}}
value=""
/>
);
};
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
getWrappedInstance = () => this.wrappedInstance;
render() {
const {
columns: originalCols,
isSelected,
toggleSelection,
toggleAll,
keyField,
selectAll,
...rest
} = this.props;
const { rowSelector, headSelector } = this;
const select = {
id: "_selector",
accessor: () => "x", // this value is not important
Header: headSelector,
Cell: ci => {
return rowSelector(ci.original);
},
width: 30,
filterable: false,
sortable: false,
resizable: false,
style: { textAlign: "center" }
};
const columns = [select, ...originalCols];
const extra = {
columns
};
return (
<Component {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
);
}
};
wrapper.displayName = "RTCheckboxTable";
wrapper.defaultProps = {
keyField: "_id",
isSelected: key => {
console.log("No isSelected handler provided:", { key });
},
selectAll: false,
toggleSelection: (key, shift, row) => {
console.log("No toggleSelection handler provided:", { key, shift, row });
},
toggleAll: () => {
console.log("No toggleAll handler provided.");
}
};
return wrapper;
};
+148
View File
@@ -0,0 +1,148 @@
import React from "react";
import shortid from "shortid";
import ReactTable from "../../../../lib/index";
import "../../../../react-table.css";
import checkboxTableHOC from "./checkboxHOC";
const CheckboxTable = checkboxTableHOC(ReactTable);
async function getData() {
const result = await (await fetch("/au_500_tree.json")).json();
// we are adding a unique ID to the data for tracking the selected records
return result.map(item => {
const _id = shortid.generate();
return {
_id,
...item
};
});
}
function getColumns(data) {
const columns = [];
const sample = data[0];
for (let key in sample) {
if (key === "_id") continue;
columns.push({
accessor: key,
Header: key
});
}
return columns;
}
export class ComponentTest extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
columns: null,
selection: [],
selectAll: false
};
}
componentDidMount() {
getData().then(data => {
const columns = getColumns(data);
this.setState({ data, columns });
});
}
toggleSelection = (key, shift, row) => {
/*
Implementation of how to manage the selection state is up to the developer.
This implementation uses an array stored in the component state.
Other implementations could use object keys, a Javascript Set, or Redux... etc.
*/
// start off with the existing state
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
};
toggleAll = () => {
/*
'toggleAll' is a tricky concept with any filterable table
do you just select ALL the records that are in your data?
OR
do you only select ALL the records that are in the current filtered data?
The latter makes more sense because 'selection' is a visual thing for the user.
This is especially true if you are going to implement a set of external functions
that act on the selected information (you would not want to DELETE the wrong thing!).
So, to that end, access to the internals of ReactTable are required to get what is
currently visible in the table (either on the current page or any other page).
The HOC provides a method call 'getWrappedInstance' to get a ref to the wrapped
ReactTable and then get the internal state and the 'sortedData'.
That can then be iterrated to get all the currently visible records and set
the selection state.
*/
const selectAll = this.state.selectAll ? false : true;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.checkboxTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we just push all the IDs onto the selection array
currentRecords.forEach(item => {
selection.push(item._original._id);
});
}
this.setState({ selectAll, selection });
};
isSelected = key => {
/*
Instead of passing our external selection state we provide an 'isSelected'
callback and detect the selection state ourselves. This allows any implementation
for selection (either an array, object keys, or even a Javascript Set object).
*/
return this.state.selection.includes(key);
};
logSelection = () => {
console.log("selection:", this.state.selection);
};
render() {
const { toggleSelection, toggleAll, isSelected, logSelection } = this;
const { data, columns, selectAll } = this.state;
const extraProps = {
selectAll,
isSelected,
toggleAll,
toggleSelection
};
return (
<div style={{ padding: "10px" }}>
<h1>react-table - Checkbox Table</h1>
<button onClick={logSelection}>Log Selection to Console</button>
{` (${this.state.selection.length}) selected`}
{data ? (
<CheckboxTable
data={data}
columns={columns}
ref={r => (this.checkboxTable = r)}
className="-striped -highlight"
{...extraProps}
/>
) : null}
</div>
);
}
}
// export default treeTableHOC(ComponentTest);
export default ComponentTest;
+60
View File
@@ -0,0 +1,60 @@
import React from "react";
export default class ComponentTest extends React.component {
render() {
return <div>Bozo</div>;
}
}
// import ReactTable from '../../../../lib/index'
// import '../../../../react-table.css'
//
// console.log('ReactTable:',ReactTable)
//
// const data = [
// {one:"1.1",two:"1.2"},
// {one:"2.1",two:"2.2"},
// {one:"3.1",two:"3.2"},
// {one:"4.1",two:"4.2"},
// ]
//
// const columns = [
// {accessor:'one', Header: 'One'},
// {accessor:'two', Header: 'Two'},
// ]
//
// class ExpanderComponent extends React.Component {
// render()
// {
// return (
// <div className={`rt-expander ${this.props.isExpanded ? '-open' : ''}`}>
// &bull;
// </div>
// )
// }
// }
//
// class SubComponent extends React.Component {
// render()
// {
// return <div>Nothing</div>
// }
// }
//
// export default class ComponentTest extends React.Component {
// render()
// {
// const rtProps = {
// data,
// columns,
// // ExpanderComponent: (props, closeExpanded)=><ExpanderComponent {...props, closeExpanded} />,
// // SubComponent: (props)=><SubComponent {...props} />,
// // multiSort: false,
// }
// return (
// <ReactTable
// {...rtProps}
// />
// )
// }
// }
@@ -0,0 +1,110 @@
import React from 'react'
import ReactTable from '../../../../lib/index'
import FoldableTableHOC from '../../../../lib/hoc/foldableTable'
import selectTableHOC from '../../../../lib/hoc/selectTable'
const FoldableTable = FoldableTableHOC(selectTableHOC(ReactTable))
export default class FoldableTableCustomState extends React.Component {
constructor(props, context) {
super(props, context)
this.state = { folded: {}, seleted: {}, selectedAll: false }
}
getData = () => [{
id: 1,
first_name: 'Jeanette',
'last_name': 'Penddreth',
email: 'jpenddreth0@census.gov',
'gender': 'Female',
ip_address: '26.58.193.2',
}, {
'id': 2,
'first_name': 'Giavani',
last_name: 'Frediani',
'email': 'gfrediani1@senate.gov',
'gender': 'Male',
'ip_address': '229.179.4.212',
}, {
'id': 3,
first_name: 'Noell',
last_name: 'Bea',
'email': 'nbea2@imageshack.us',
gender: 'Female',
ip_address: '180.66.162.255',
}, {
'id': 4,
'first_name': 'Willard',
'last_name': 'Valek',
email: 'wvalek3@vk.com',
'gender': 'Male',
ip_address: '67.76.188.26',
}];
toggleSelection = (key, shift, row) => {
const { selected } = this.state
let newSelected = Object.assign({}, selected)
newSelected[key] = !newSelected[key]
this.setState(p => ({ selected: newSelected }))
};
toggleAll = () => {
const { selectedAll } = this.state
if (selectedAll) { this.setState(p => { return { selectedAll: false, seleted: {} } }); }
else {
const data = this.getData()
let newSelected = {}
data.forEach(d => newSelected[d.id] = true)
this.setState(p => ({ selectedAll: true, seleted: newSelected }))
}
}
isSelected = key => this.state.seleted[key];
render() {
return (<FoldableTable
//SelectTable props
keyField='id'
toggleSelection={this.toggleSelection}
toggleAll={this.toggleAll}
isSelected={this.isSelected}
selectAll={this.state.selectedAll}
selectType='checkbox'
onFoldChange={newFolded => this.setState(p => { return { folded: newFolded } })}
folded={this.state.folded}
data={this.getData()}
columns={[{
Header: "Name",
foldable: true,
columns: [
{
Header: "First Name",
accessor: "first_name"
},
{
Header: "Last Name",
accessor: "last_name"
}
]
}, {
Header: "Info",
foldable: true,
columns: [
{
Header: "Email",
accessor: "email"
},
{
Header: "Gender",
accessor: "gender"
}
]
}]
}></FoldableTable>)
}
}
@@ -0,0 +1,71 @@
import React from 'react'
import ReactTable from '../../../../lib/index'
import FoldableTableHOC from '../../../../lib/hoc/foldableTable'
const FoldableTable = FoldableTableHOC(ReactTable)
export default class FoldableTableWithHeader extends React.Component {
getData = () => [{
id: 1,
first_name: 'Jeanette',
last_name: 'Penddreth',
'email': 'jpenddreth0@census.gov',
gender: 'Female',
'ip_address': '26.58.193.2',
}, {
'id': 2,
first_name: 'Giavani',
last_name: 'Frediani',
email: 'gfrediani1@senate.gov',
gender: 'Male',
'ip_address': '229.179.4.212',
}, {
'id': 3,
'first_name': 'Noell',
last_name: 'Bea',
'email': 'nbea2@imageshack.us',
'gender': 'Female',
ip_address: '180.66.162.255',
}, {
'id': 4,
'first_name': 'Willard',
'last_name': 'Valek',
email: 'wvalek3@vk.com',
'gender': 'Male',
ip_address: '67.76.188.26',
}];
render() {
return (<FoldableTable
data={this.getData()}
columns={[{
Header: "Name",
foldable: true,
columns: [
{
Header: "First Name",
accessor: "first_name"
},
{
Header: "Last Name",
accessor: "last_name"
}
]
}, {
Header: "Info",
foldable: true,
columns: [
{
Header: "Email",
accessor: "email"
},
{
Header: "Gender",
accessor: "gender"
}
]
}]
}></FoldableTable>)
}
}
@@ -0,0 +1,64 @@
import React from 'react';
import ReactTable from '../../../../lib/index';
import FoldableTableHOC from '../../../../lib/hoc/foldableTable';
const FoldableTable = FoldableTableHOC(ReactTable);
export default class FoldableTableWithoutHeader extends React.Component {
getData = () => [{
"id": 1,
"first_name": "Jeanette",
"last_name": "Penddreth",
"email": "jpenddreth0@census.gov",
"gender": "Female",
"ip_address": "26.58.193.2"
}, {
"id": 2,
"first_name": "Giavani",
"last_name": "Frediani",
"email": "gfrediani1@senate.gov",
"gender": "Male",
"ip_address": "229.179.4.212"
}, {
"id": 3,
"first_name": "Noell",
"last_name": "Bea",
"email": "nbea2@imageshack.us",
"gender": "Female",
"ip_address": "180.66.162.255"
}, {
"id": 4,
"first_name": "Willard",
"last_name": "Valek",
"email": "wvalek3@vk.com",
"gender": "Male",
"ip_address": "67.76.188.26"
}];
render() {
return <FoldableTable
data={this.getData()}
columns={[
{
Header: "First Name",
accessor: "first_name"
},
{
Header: "Last Name",
accessor: "last_name",
foldable: true,
},
{
Header: "Email",
accessor: "email",
foldable: true,
},
{
Header: "Gender",
accessor: "gender",
foldable: true,
}
]}></FoldableTable>
}
}
+30
View File
@@ -0,0 +1,30 @@
import React from 'react'
import '../../../../react-table.css'
import FoldableTableWithHeader from './FoldableTableWithHeader'
import FoldableTableWithoutHeader from './FoldableTableWithoutHeader'
import FoldableTableCustomState from './FoldableTableCustomState'
class FaldableComponentTest extends React.Component {
render() {
return (
<div>
<p>- Sample With Header Columns</p>
<br />
<FoldableTableWithHeader />
<br /> <br />
<p>- Sample With Normal Columns</p>
<br />
<FoldableTableWithoutHeader />
<br /> <br />
<p>- Custom State and selectedTable</p>
<br />
<FoldableTableCustomState />
</div >
)
}
}
export default FaldableComponentTest
+13
View File
@@ -0,0 +1,13 @@
/* eslint-disable */
import TreeTable from './treetable'
import SelectTable from './selecttable'
import SelectTreeTable from './selecttreetable'
import FoldableTable from './foldabletable';
export {
TreeTable,
SelectTable,
SelectTreeTable,
FoldableTable
}
+173
View File
@@ -0,0 +1,173 @@
import React from "react";
import shortid from "shortid";
import ReactTable from "../../../../lib/index";
import "../../../../react-table.css";
import selectTableHOC from "../../../../lib/hoc/selectTable";
const SelectTable = selectTableHOC(ReactTable);
async function getData() {
const result = await (await fetch("/au_500_tree.json")).json();
// we are adding a unique ID to the data for tracking the selected records
return result.map(item => {
const _id = shortid.generate();
return {
_id,
...item
};
});
}
function getColumns(data) {
const columns = [];
const sample = data[0];
for (let key in sample) {
if (key === "_id") continue;
columns.push({
accessor: key,
Header: key
});
}
return columns;
}
export class ComponentTest extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
columns: null,
selection: [],
selectAll: false,
selectType: "checkbox"
};
}
componentDidMount() {
getData().then(data => {
const columns = getColumns(data);
this.setState({ data, columns });
});
}
toggleSelection = (key, shift, row) => {
/*
Implementation of how to manage the selection state is up to the developer.
This implementation uses an array stored in the component state.
Other implementations could use object keys, a Javascript Set, or Redux... etc.
*/
// start off with the existing state
if (this.state.selectType === "radio") {
let selection = [];
if (selection.indexOf(key) < 0) selection.push(key);
this.setState({ selection });
} else {
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
};
toggleAll = () => {
/*
'toggleAll' is a tricky concept with any filterable table
do you just select ALL the records that are in your data?
OR
do you only select ALL the records that are in the current filtered data?
The latter makes more sense because 'selection' is a visual thing for the user.
This is especially true if you are going to implement a set of external functions
that act on the selected information (you would not want to DELETE the wrong thing!).
So, to that end, access to the internals of ReactTable are required to get what is
currently visible in the table (either on the current page or any other page).
The HOC provides a method call 'getWrappedInstance' to get a ref to the wrapped
ReactTable and then get the internal state and the 'sortedData'.
That can then be iterrated to get all the currently visible records and set
the selection state.
*/
const selectAll = this.state.selectAll ? false : true;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.selectTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we just push all the IDs onto the selection array
currentRecords.forEach(item => {
if (item._original) {
selection.push(item._original._id);
}
});
}
this.setState({ selectAll, selection });
};
isSelected = key => {
/*
Instead of passing our external selection state we provide an 'isSelected'
callback and detect the selection state ourselves. This allows any implementation
for selection (either an array, object keys, or even a Javascript Set object).
*/
return this.state.selection.includes(key);
};
logSelection = () => {
console.log("selection:", this.state.selection);
};
toggleType = () => {
this.setState({
selectType: this.state.selectType === "radio" ? "checkbox" : "radio",
selection: [],
selectAll: false
});
};
render() {
const {
toggleSelection,
toggleAll,
isSelected,
logSelection,
toggleType
} = this;
const { data, columns, selectAll, selectType } = this.state;
const extraProps = {
selectAll,
isSelected,
toggleAll,
toggleSelection,
selectType
};
return (
<div style={{ padding: "10px" }}>
<h1>react-table - Select Table</h1>
<button onClick={toggleType}>
Select Type: <strong>{selectType}</strong>
</button>
<button onClick={logSelection}>Log Selection to Console</button>
{` (${this.state.selection.length}) selected`}
{data ? (
<SelectTable
data={data}
columns={columns}
ref={r => (this.selectTable = r)}
className="-striped -highlight"
{...extraProps}
/>
) : null}
</div>
);
}
}
export default ComponentTest;
+238
View File
@@ -0,0 +1,238 @@
import React from "react";
import shortid from "shortid";
import ReactTable from "../../../../lib/index";
import "../../../../react-table.css";
import selectTableHOC from "../../../../lib/hoc/selectTable";
import treeTableHOC from "../../../../lib/hoc/treeTable";
const SelectTreeTable = selectTableHOC(treeTableHOC(ReactTable));
async function getData() {
const result = await (await fetch("/au_500_tree.json")).json();
// we are adding a unique ID to the data for tracking the selected records
return result.map(item => {
const _id = shortid.generate();
return {
_id,
...item
};
});
}
function getColumns(data) {
const columns = [];
const sample = data[0];
for (let key in sample) {
if (key === "_id") continue;
columns.push({
accessor: key,
Header: key
});
}
return columns;
}
function getNodes(data, node = []) {
data.forEach(item => {
if (item.hasOwnProperty("_subRows") && item._subRows) {
node = getNodes(item._subRows, node);
} else {
node.push(item._original);
}
});
return node;
}
export class ComponentTest extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
columns: null,
selection: [],
selectAll: false,
selectType: "checkbox"
};
}
componentDidMount() {
getData().then(data => {
const columns = getColumns(data);
const pivotBy = ["state", "post"];
this.setState({ data, columns, pivotBy });
});
}
toggleSelection = (key, shift, row) => {
/*
Implementation of how to manage the selection state is up to the developer.
This implementation uses an array stored in the component state.
Other implementations could use object keys, a Javascript Set, or Redux... etc.
*/
// start off with the existing state
if (this.state.selectType === "radio") {
let selection = [];
if (selection.indexOf(key) < 0) selection.push(key);
this.setState({ selection });
} else {
let selection = [...this.state.selection];
const keyIndex = selection.indexOf(key);
// check to see if the key exists
if (keyIndex >= 0) {
// it does exist so we will remove it using destructing
selection = [
...selection.slice(0, keyIndex),
...selection.slice(keyIndex + 1)
];
} else {
// it does not exist so add it
selection.push(key);
}
// update the state
this.setState({ selection });
}
};
toggleAll = () => {
/*
'toggleAll' is a tricky concept with any filterable table
do you just select ALL the records that are in your data?
OR
do you only select ALL the records that are in the current filtered data?
The latter makes more sense because 'selection' is a visual thing for the user.
This is especially true if you are going to implement a set of external functions
that act on the selected information (you would not want to DELETE the wrong thing!).
So, to that end, access to the internals of ReactTable are required to get what is
currently visible in the table (either on the current page or any other page).
The HOC provides a method call 'getWrappedInstance' to get a ref to the wrapped
ReactTable and then get the internal state and the 'sortedData'.
That can then be iterrated to get all the currently visible records and set
the selection state.
*/
const selectAll = this.state.selectAll ? false : true;
const selection = [];
if (selectAll) {
// we need to get at the internals of ReactTable
const wrappedInstance = this.selectTable.getWrappedInstance();
// the 'sortedData' property contains the currently accessible records based on the filter and sort
const currentRecords = wrappedInstance.getResolvedState().sortedData;
// we need to get all the 'real' (original) records out to get at their IDs
const nodes = getNodes(currentRecords);
// we just push all the IDs onto the selection array
nodes.forEach(item => {
selection.push(item._id);
});
}
this.setState({ selectAll, selection });
};
isSelected = key => {
/*
Instead of passing our external selection state we provide an 'isSelected'
callback and detect the selection state ourselves. This allows any implementation
for selection (either an array, object keys, or even a Javascript Set object).
*/
return this.state.selection.includes(key);
};
logSelection = () => {
console.log("selection:", this.state.selection);
};
toggleType = () => {
this.setState({
selectType: this.state.selectType === "radio" ? "checkbox" : "radio",
selection: [],
selectAll: false
});
};
toggleTree = () => {
if (this.state.pivotBy.length) {
this.setState({ pivotBy: [], expanded: {} });
} else {
this.setState({ pivotBy: ["state", "post"], expanded: {} });
}
};
onExpandedChange = expanded => {
this.setState({ expanded });
};
render() {
const {
toggleSelection,
toggleAll,
isSelected,
logSelection,
toggleType,
toggleTree,
onExpandedChange
} = this;
const {
data,
columns,
selectAll,
selectType,
pivotBy,
expanded
} = this.state;
const extraProps = {
selectAll,
isSelected,
toggleAll,
toggleSelection,
selectType,
pivotBy,
expanded,
onExpandedChange,
pageSize: 5
};
return (
<div style={{ padding: "10px" }}>
<h1>react-table - Select Tree Table</h1>
<p>
This example combines two HOCs (the TreeTable and the SelectTable) to
make a composite component.
</p>
<p>We'll call it SelectTreeTable!</p>
<p>Here is what the buttons do:</p>
<ul>
<li>
<strong>Toggle Tree:</strong> enables or disabled the pivotBy on the
table.
</li>
<li>
<strong>Select Type:</strong> changes from 'checkbox' to 'radio' and
back again.
</li>
<li>
<strong>Log Selection to Console:</strong> open your console to see
what has been selected.
</li>
</ul>
<p>
<strong>NOTE:</strong> the selection is maintained when toggling the
tree on and off but is cleared when switching between select types
(radio, checkbox).
</p>
<button onClick={toggleTree}>
Toggle Tree [{pivotBy && pivotBy.length ? pivotBy.join(", ") : ""}]
</button>
<button onClick={toggleType}>
Select Type: <strong>{selectType}</strong>
</button>
<button onClick={logSelection}>Log Selection to Console</button>
{` (${this.state.selection.length}) selected`}
{data ? (
<SelectTreeTable
data={data}
columns={columns}
ref={r => (this.selectTable = r)}
className="-striped -highlight"
freezeWhenExpanded={true}
{...extraProps}
/>
) : null}
</div>
);
}
}
export default ComponentTest;
+70
View File
@@ -0,0 +1,70 @@
import React from "react";
import ReactTable from "../../../../lib/index";
import "../../../../react-table.css";
import treeTableHOC from "../../../../lib/hoc/treeTable";
async function getData() {
const result = await (await fetch("/au_500_tree.json")).json();
return result;
}
function getColumns(data, pivotBy) {
const columns = [];
const sample = data[0];
for (let key in sample) {
columns.push({
accessor: key,
Header: key
});
}
return columns;
}
export class ComponentTest extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
columns: null,
pivotBy: null // ["firstName", "lastName"],
};
}
componentDidMount() {
getData().then(data => {
// console.log('cwm data:',data);
const pivotBy = ["state", "post", "city"];
const columns = getColumns(data, pivotBy);
// console.log('cwm cols:',columns);
this.setState({ data, columns, pivotBy });
});
}
showState = () => {
console.log("state:", this.reactTable.getResolvedState());
};
render() {
const { data, columns, pivotBy } = this.state;
const extraProps = {
data,
columns,
pivotBy
};
const TreeTable = treeTableHOC(ReactTable);
return (
<div style={{ padding: "10px" }}>
<h1>react-table - Tree Table</h1>
{data ? (
<TreeTable
ref={r => (this.reactTable = r)}
className="-striped -highlight"
defaultPageSize={5}
{...extraProps}
/>
) : null}
</div>
);
}
}
export default ComponentTest;
@@ -0,0 +1,53 @@
import React from "react";
export default Component => {
const wrapper = componentProps => {
const TrComponent = props => {
const { ri, ...rest } = props;
if (ri && ri.groupedByPivot) {
const cell = props.children[ri.level];
cell.props.style.flex = "unset";
cell.props.style.width = "100%";
cell.props.style.maxWidth = "unset";
cell.props.style.paddingLeft = `${componentProps.treeTableIndent *
ri.level}px`;
cell.props.style.backgroundColor = "#DDD";
cell.props.style.borderBottom = "1px solid rgba(128,128,128,0.2)";
return <div {...rest}>{cell}</div>;
}
return <Component.defaultProps.TrComponent {...rest} />;
};
const getTrProps = (state, ri, ci, instance) => {
return { ri };
};
const { columns, ...rest } = componentProps;
const extra = {
columns: columns.map(col => {
let column = col;
if (rest.pivotBy && rest.pivotBy.includes(col.accessor)) {
column = {
accessor: col.accessor,
width: `${componentProps.treeTableIndent}px`,
show: false,
Header: ""
};
}
return column;
}),
TrComponent,
getTrProps
};
return <Component {...rest} {...extra} />;
};
wrapper.displayName = "RTTreeTable";
wrapper.defaultProps = {
treeTableRowBackground: "#EEE",
treeTableIndent: 10
};
return wrapper;
};
+35
View File
@@ -0,0 +1,35 @@
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 function makeData(len = 5553) {
return range(len).map(d => {
return {
...newPerson(),
children: range(10).map(newPerson)
};
});
}
+4 -2
View File
@@ -1,5 +1,7 @@
html, body, #root {
height: 100%
html,
body,
#root {
height: 100%;
}
body {
margin: 0;
+5 -8
View File
@@ -1,10 +1,7 @@
import React from 'react'
import ReactDOM from 'react-dom'
import React from "react";
import ReactDOM from "react-dom";
//
import './index.css'
import App from './App.js'
import "./index.css";
import App from "./App.js";
ReactDOM.render(
<App />,
document.getElementById('root')
)
ReactDOM.render(<App />, document.getElementById("root"));
-109
View File
@@ -1,109 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
progress: Math.floor(Math.random() * 100),
status: statusChance > 0.66 ? 'relationship'
: statusChance > 0.33 ? 'complicated'
: 'single'
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Profile Progress',
accessor: 'progress',
Cell: row => (
<div
style={{
width: '100%',
height: '100%',
backgroundColor: '#dadada',
borderRadius: '2px'
}}
>
<div
style={{
width: `${row.value}%`,
height: '100%',
backgroundColor: row.value > 66 ? '#85cc00'
: row.value > 33 ? '#ffbf00'
: '#ff2e00',
borderRadius: '2px',
transition: 'all .2s ease-out'
}}
/>
</div>
)
}, {
Header: 'Status',
accessor: 'status',
Cell: row => (
<span>
<span style={{
color: row.value === 'relationship' ? '#ff2e00'
: row.value === 'complicated' ? '#ffbf00'
: '#57d500',
transition: 'all .3s ease'
}}>
&#x25cf;
</span> {
row.value === 'relationship' ? 'In a relationship'
: row.value === 'complicated' ? `It's complicated`
: 'Single'
}
</span>
)
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./CellRenderers')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-89
View File
@@ -1,89 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
class Story extends React.PureComponent {
constructor () {
super()
this.state = {
sorted: [],
page: 0,
pageSize: 10,
expanded: {},
resized: [],
filtered: []
}
}
render () {
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
pivotBy={['lastName']}
filterable
// Controlled Props
sorted={this.state.sorted}
page={this.state.page}
pageSize={this.state.pageSize}
expanded={this.state.expanded}
resized={this.state.resized}
filtered={this.state.filtered}
// Callbacks
onSortedChange={sorted => this.setState({sorted})}
onPageChange={page => this.setState({page})}
onPageSizeChange={(pageSize, page) => this.setState({page, pageSize})}
onExpandedChange={expanded => this.setState({expanded})}
onResizedChange={resized => this.setState({resized})}
onFilteredChange={filtered => this.setState({filtered})}
/>
</div>
<br />
<pre><code><strong>this.state ===</strong> {JSON.stringify(this.state, null, 2)}</code></pre>
<br />
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./ControlledTable')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-76
View File
@@ -1,76 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<strong>Hey!</strong> Open your console! :)
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
getTdProps={(state, rowInfo, column, instance) => {
return {
onMouseEnter: e => console.log('Cell - onMouseEnter', {
state,
rowInfo,
column,
instance,
event: e
})
}
}}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./CustomComponentProps')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
@@ -1,81 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({words: 1, numbers: 0}),
lastName: namor.generate({words: 1, numbers: 0}),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
Footer: () => <div style={{textAlign: 'center'}}>First Name</div>
}, {
Header: 'Last Name',
accessor: 'lastName',
Footer: () => <div style={{textAlign: 'center'}}>Last Name</div>
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
Footer: () => <div style={{textAlign: 'center'}}>Age</div>
}]
}, {
Header: 'Expand',
columns: [{
expander: true,
Header: () => (<strong>More</strong>),
width: 65,
Expander: ({isExpanded, ...rest}) => (
<div>
{isExpanded ? <span>&#x2299;</span> : <span>&#x2295;</span>}
</div>
),
style: {cursor: 'pointer', fontSize: 25, padding: '0', textAlign: 'center', userSelect: 'none'},
Footer: () => <span>&hearts;</span>
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
SubComponent={() => <span>Hello</span>}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./CustomExpanderPosition')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-78
View File
@@ -1,78 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name (Sorted by Length, A-Z)',
accessor: 'firstName',
sortMethod: (a, b) => {
if (a.length === b.length) {
return a > b ? 1 : -1
}
return a.length > b.length ? 1 : -1
}
}, {
Header: 'Last Name (Sorted in reverse, A-Z)',
id: 'lastName',
accessor: d => d.lastName,
sortMethod: (a, b) => {
if (a === b) {
return 0
}
const aReverse = a.split('').reverse().join('')
const bReverse = b.split('').reverse().join('')
return aReverse > bReverse ? 1 : -1
}
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./CustomSorting')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-67
View File
@@ -1,67 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
maxWidth: 200
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName,
width: 300
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
minWidth: 400
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./CustomWidths')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-68
View File
@@ -1,68 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
defaultSorted={[{
id: 'age',
desc: true
}]}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./DefaultSorting')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-70
View File
@@ -1,70 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
constructor (props, context) {
super(props, context)
this.renderEditable = this.renderEditable.bind(this)
this.state = {
data: [
{ firstName: 'Lucy', lastName: 'Marks' },
{ firstName: 'Bejamin', lastName: 'Pike' }
]
}
this.columns = [
{
Header: 'First Name',
accessor: 'firstName',
Cell: this.renderEditable
},
{
Header: 'Last Name',
accessor: 'lastName',
Cell: this.renderEditable
},
{
Header: 'Full Name',
id: 'full',
accessor: d => d.firstName + ' ' + d.lastName
}
]
}
renderEditable (cellInfo) {
return (<div style={{ backgroundColor: '#fafafa' }} contentEditable suppressContentEditableWarning onBlur={(e) => {
const data = [...this.state.data]
data[cellInfo.index][cellInfo.column.id] = e.target.textContent
this.setState({data: data})
}}>{this.state.data[cellInfo.index][cellInfo.column.id]}</div>)
}
render () {
return (
<div className='table-wrap' style={{marginBottom: '20px'}}>
<p>First two columns are editable just by clicking into them using the <code>contentEditable</code> attribute. Last column (Full Name) is computed from the first two.</p>
<ReactTable
data={this.state.data}
columns={this.columns}
defaultPageSize={2}
showPageSizeOptions={false}
showPagination={false}
/>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./EditableTable')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-194
View File
@@ -1,194 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import CodeHighlight from './components/codeHighlight'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
constructor (props) {
super(props)
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({words: 1, numbers: 0}),
lastName: namor.generate({words: 1, numbers: 0}),
age: Math.floor(Math.random() * 30)
}
})
this.state = {
tableOptions: {
loading: false,
showPagination: true,
showPageSizeOptions: true,
showPageJump: true,
collapseOnSortingChange: true,
collapseOnPageChange: true,
collapseOnDataChange: true,
freezeWhenExpanded: false,
filterable: true,
sortable: true,
resizable: true
},
data: data
}
this.setTableOption = this.setTableOption.bind(this)
}
render () {
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
filterMethod: (filter, row) => (row[filter.id].startsWith(filter.value) && row[filter.id].endsWith(filter.value))
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName,
filterMethod: (filter, row) => (row[filter.id].includes(filter.value))
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}, {
Header: 'Over 21',
accessor: 'age',
id: 'over',
Cell: ({value}) => (value >= 21 ? 'Yes' : 'No'),
filterMethod: (filter, row) => {
if (filter.value === 'all') {
return true
}
if (filter.value === 'true') {
return row[filter.id] >= 21
}
return row[filter.id] < 21
},
Filter: ({filter, onChange}) => (
<select
onChange={event => onChange(event.target.value)}
style={{width: '100%'}}
value={filter ? filter.value : 'all'}
>
<option value='all' />
<option value='true'>Can Drink</option>
<option value='false'>Can't Drink</option>
</select>
)
}
]
}]
return (
<div>
<div>
<h1>Table Options</h1>
<table>
<tbody>
{
Object.keys(this.state.tableOptions).map(optionKey => {
const optionValue = this.state.tableOptions[optionKey]
return (
<tr key={optionKey}>
<td>{optionKey}</td>
<td style={{paddingLeft: 10, paddingTop: 5}}>
<input type='checkbox'
name={optionKey}
checked={optionValue}
onChange={this.setTableOption}
/>
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={this.state.data}
columns={columns}
defaultPageSize={10}
defaultFilterMethod={(filter, row) => (String(row[filter.id]) === filter.value)}
{...this.state.tableOptions}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>You can put any component you want here, even another React Table!</em>
<br />
<br />
<ReactTable
data={this.state.data}
columns={columns}
defaultPageSize={3}
showPagination={false}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>It even has access to the row data: </em>
<CodeHighlight>{() => JSON.stringify(row, null, 2)}</CodeHighlight>
</div>
)
}}
/>
</div>
)
}}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
<div>
<h1>Custom Filters In This Example</h1>
<p>The default filter for all columns of a table if it is not specified in the configuration is set to match
on values that start with the filter text. Example: age.startsWith("2").</p>
<p>This example overrides the default filter behavior by setting
the <strong>defaultFilterMethod</strong> table option to match on values that are exactly equal to the
filter text. Example: age == "23")</p>
<p>Each column can also be customized with the column <strong>filterMethod</strong> option:</p>
<p>In this example the firstName column filters on the value starting with and ending with the filter
value.</p>
<p>In this example the lastName column filters on the value including the filter value anywhere in its
text.</p>
<p>To completely override the filter that is shown, you can set the <strong>Filter</strong> column
option. Using this option you can specify the JSX that is shown. The option is passed
an <strong>onChange</strong> method that must be called with the value that you wan't to
pass to the <strong>filterMethod</strong> option whenever the filter has changed.</p>
</div>
</div>
)
}
setTableOption (event) {
const target = event.target
const value = target.type === 'checkbox' ? target.checked : target.value
const name = target.name
this.setState({
tableOptions: {
...this.state.tableOptions,
[name]: value
}
})
}
}
// Source Code
const source = require('!raw!./Filtering')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-81
View File
@@ -1,81 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render() {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
children: _.map(_.range(10), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
}
})
const columns = [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName'
},
{
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}
]
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age'
}
]
}
]
return (
<div>
<div className="table-wrap">
<ReactTable
className="-striped -highlight"
data={data}
columns={columns}
defaultPageSize={20}
style={{
height: '400px' // This will force the table body to overflow and scroll, since there is not enough room
}}
/>
</div>
<div style={{ textAlign: 'center' }}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./Simple')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-92
View File
@@ -1,92 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
Footer: (
<span><strong>Popular:</strong> {
_.first(
_.reduce(
_.map(
_.groupBy(
data, d => d.firstName
)
),
(a, b) => a.length > b.length ? a : b
)
).firstName}
</span>
)
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName,
Footer: (
<span><strong>Longest:</strong> {
_.reduce(
_.map(
_.groupBy(
data, d => d.lastName
),
(d, key) => key
),
(a, b) => a.length > b.length ? a : b
)}
</span>
)
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
Footer: <span><strong>Average:</strong> {_.round(_.mean(_.map(data, d => d.age)))}</span>
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./Footers')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-137
View File
@@ -1,137 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import JSONTree from 'react-json-tree'
import ReactTable from '../../../lib/index'
const JSONtheme = {
scheme: 'monokai',
author: 'wimer hazenberg (http://www.monokai.nl)',
base00: '#272822',
base01: '#383830',
base02: '#49483e',
base03: '#75715e',
base04: '#a59f85',
base05: '#f8f8f2',
base06: '#f5f4f1',
base07: '#f9f8f5',
base08: '#f92672',
base09: '#fd971f',
base0A: '#f4bf75',
base0B: '#a6e22e',
base0C: '#a1efe4',
base0D: '#66d9ef',
base0E: '#ae81ff',
base0F: '#cc6633'
}
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
Footer: 'Footer'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName,
Footer: 'Footer'
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
Footer: 'Footer'
}]
}]
return (
<div>
<strong>Functional rendering</strong> simply means that you have all of the building blocks to render your own React Table however you'd like.
<br />
<br />
<br />
<br />
<strong>Decorating the standard table output</strong>
<br />
<br />
<div className='table-wrap'>
<ReactTable
data={data}
columns={columns}
>
{(state, makeTable, instance) => {
return (
<div style={{
background: '#ffcf00',
borderRadius: '5px',
overflow: 'hidden',
padding: '5px'
}}>
<pre><code>state.allVisibleColumns === {JSON.stringify(state.allVisibleColumns, null, 4)}</code></pre>
{makeTable()}
</div>
)
}}
</ReactTable>
</div>
<br />
<br />
<strong>Need more control? This is the entire table state and component instance at your disposal!</strong>
<br />
<br />
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
>
{(state, StandardTable, instance) => {
return (
<div>
<JSONTree
data={Object.assign({}, state, {children: 'function () {...}'})}
theme={JSONtheme}
invertTheme
/>
</div>
)
}}
</ReactTable>
</div>
<br />
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./FunctionalRendering')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
+23
View File
@@ -0,0 +1,23 @@
/* eslint-disable */
import React from "react";
import marked from "marked";
//
import HOCReadme from "!raw!../../../src/hoc/README.md";
import "github-markdown-css/github-markdown.css";
import "./utils/prism.js";
export default class HOCStory extends React.Component {
render() {
return (
<div style={{ padding: "10px" }}>
<span
className="markdown-body"
dangerouslySetInnerHTML={{ __html: marked(HOCReadme) }}
/>
</div>
);
}
componentDidMount() {
global.Prism && global.Prism.highlightAll();
}
}
-73
View File
@@ -1,73 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
children: _.map(_.range(10), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
showPagination
showPaginationTop
showPaginationBottom
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./MultiplePagers')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-57
View File
@@ -1,57 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={[]}
noDataText='Oh Noes!'
// noDataText={() => 'Oh Noes!'} // Supports functions
// noDataText={() => <span>Oh Noes!</span>} // Supports JSX / React Components
columns={columns}
defaultPageSize={10}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./NoDataText')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-97
View File
@@ -1,97 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(100000), d => {
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)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
aggregate: vals => _.round(_.mean(vals)),
Aggregated: row => {
return <span>{row.value} (avg)</span>
}
}, {
Header: 'Visits',
accessor: 'visits',
aggregate: vals => _.sum(vals)
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
data={data}
columns={columns}
className='-striped -highlight'
defaultPageSize={10}
pivotBy={['firstName', 'lastName']}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>You can put any component you want here, even another React Table!</em>
<br />
<br />
<ReactTable
data={data}
columns={columns}
defaultPageSize={3}
showPagination={false}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>It even has access to the row data: </em>
<CodeHighlight>{() => JSON.stringify(row, null, 2)}</CodeHighlight>
</div>
)
}}
/>
</div>
)
}}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./OneHundredKRows')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-74
View File
@@ -1,74 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(1000), d => {
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)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
aggregate: vals => _.round(_.mean(vals)),
Aggregated: row => {
return <span>{row.value} (avg)</span>
}
}, {
Header: 'Visits',
accessor: 'visits',
aggregate: vals => _.sum(vals)
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
data={data}
columns={columns}
className='-striped -highlight'
defaultPageSize={10}
pivotBy={['firstName', 'lastName']}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./Pivoting')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-132
View File
@@ -1,132 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(1000), d => {
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)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
PivotValue: ({value}) => <span style={{color: 'darkred'}}>{value}</span>
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName,
PivotValue: ({value}) => <span style={{color: 'darkblue'}}>{value}</span>,
Footer: () => <div style={{textAlign: 'center'}}><strong>Pivot Column Footer</strong></div>
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
aggregate: vals => {
return _.round(_.mean(vals))
},
Aggregated: row => <span>{row.value} (avg)</span>
}, {
Header: 'Visits',
accessor: 'visits',
aggregate: vals => _.sum(vals),
filterable: false
}]
}, {
pivot: true,
Header: () => <strong>Overridden Pivot Column Header Group</strong>
}, {
expander: true
}]
const subtableColumns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName'
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}, {
Header: 'Visits',
accessor: 'visits'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
data={data}
columns={columns}
defaultPageSize={10}
className='-striped -highlight'
pivotBy={['firstName', 'lastName']}
defaultSorted={[{id: 'firstName', desc: false}, {id: 'lastName', desc: true}]}
collapseOnSortingChange={false}
filterable
ExpanderComponent={({isExpanded, ...rest}) => (
isExpanded ? <span> &#10136; </span> : <span> &#10137; </span>
)}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>You can put any component you want here, even another React Table!</em>
<br />
<br />
<ReactTable
data={data}
columns={subtableColumns}
defaultPageSize={3}
showPagination={false}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>It even has access to the row data: </em>
<CodeHighlight>{() => JSON.stringify(row, null, 2)}</CodeHighlight>
</div>
)
}}
/>
</div>
)
}}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./PivotingOptions')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-100
View File
@@ -1,100 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(1000), d => {
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)
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age',
aggregate: vals => _.round(_.mean(vals)),
Aggregated: row => {
return <span>{row.value} (avg)</span>
},
filterMethod: (filter, row) => (filter.value === `${row[filter.id]} (avg)`)
}, {
Header: 'Visits',
accessor: 'visits',
aggregate: vals => _.sum(vals),
filterable: false
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
data={data}
columns={columns}
defaultPageSize={10}
className='-striped -highlight'
pivotBy={['firstName', 'lastName']}
filterable
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>You can put any component you want here, even another React Table!</em>
<br />
<br />
<ReactTable
data={data}
columns={columns}
defaultPageSize={3}
showPagination={false}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>It even has access to the row data: </em>
<CodeHighlight>{() => JSON.stringify(row, null, 2)}</CodeHighlight>
</div>
)
}}
/>
</div>
)
}}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./PivotingSubComponents')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
+13 -10
View File
@@ -1,20 +1,23 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import marked from 'marked'
import React from "react";
import marked from "marked";
//
import Readme from '!raw!../../../README.md'
import 'github-markdown-css/github-markdown.css'
import Readme from "!raw!../../../README.md";
import "github-markdown-css/github-markdown.css";
import "./utils/prism.js";
export default class Story extends React.Component {
render() {
return (
<span
className="markdown-body"
dangerouslySetInnerHTML={{ __html: marked(Readme) }}
/>
)
<div style={{ padding: "10px" }}>
<span
className="markdown-body"
dangerouslySetInnerHTML={{ __html: marked(Readme) }}
/>
</div>
);
}
componentDidMount() {
global.Prism.highlightAll()
global.Prism && global.Prism.highlightAll();
}
}
-121
View File
@@ -1,121 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
const rawData = _.map(_.range(3424), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
// Now let's mock the server. It's job is simple: use the table model to sort and return the page data
const requestData = (pageSize, page, sorted, filtered) => {
return new Promise((resolve, reject) => {
// On the server, you'll likely use SQL or noSQL or some other query language to do this.
// For this mock, we'll just use lodash
let filteredData = rawData
if (filtered.length) {
filteredData = filtered.reduce(
(filteredSoFar, nextFilter) => {
return filteredSoFar.filter(
(row) => {
return (row[nextFilter.id] + '').includes(nextFilter.value)
})
}
, filteredData)
}
const sortedData = _.orderBy(filteredData, sorted.map(sort => {
return row => {
if (row[sort.id] === null || row[sort.id] === undefined) {
return -Infinity
}
return typeof row[sort.id] === 'string' ? row[sort.id].toLowerCase() : row[sort.id]
}
}), sorted.map(d => d.desc ? 'desc' : 'asc'))
// Be sure to send back the rows to be displayed and any other pertinent information, like how many pages there are total.
const res = {
rows: sortedData.slice(pageSize * page, (pageSize * page) + pageSize),
pages: Math.ceil(filteredData.length / pageSize)
}
// Here we'll simulate a server response with 500ms of delay.
setTimeout(() => resolve(res), 500)
})
}
class Story extends React.PureComponent {
constructor () {
super()
this.state = {
data: [],
pages: null,
loading: true
}
this.fetchData = this.fetchData.bind(this)
}
fetchData (state, instance) {
// Whenever the table model changes, or the user sorts or changes pages, this method gets called and passed the current table model.
// You can set the `loading` prop of the table to true to use the built-in one or show you're own loading bar if you want.
this.setState({loading: true})
// Request the data however you want. Here, we'll use our mocked service we created earlier
requestData(state.pageSize, state.page, state.sorted, state.filtered)
.then((res) => {
// Now just get the rows of data to your React Table (and update anything else like total pages or loading)
this.setState({
data: res.rows,
pages: res.pages,
loading: false
})
})
}
render () {
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
columns={[{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}, {
Header: 'Age',
accessor: 'age'
}]}
manual // Forces table not to paginate or sort automatically, so we can handle it server-side
defaultPageSize={10}
filterable
data={this.state.data} // Set the rows to be displayed
pages={this.state.pages} // Display the total number of pages
loading={this.state.loading} // Display the loading overlay when we need it
onFetchData={this.fetchData} // Request new data when things change
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./ServerSide')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-70
View File
@@ -1,70 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
children: _.map(_.range(10), d => {
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30)
}
})
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./Simple')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-146
View File
@@ -1,146 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
constructor (props) {
super(props)
const data = _.map(_.range(5553), d => {
return {
firstName: namor.generate({words: 1, numbers: 0}),
lastName: namor.generate({words: 1, numbers: 0}),
age: Math.floor(Math.random() * 30)
}
})
this.state = {
tableOptions: {
loading: false,
showPagination: true,
showPageSizeOptions: true,
showPageJump: true,
collapseOnSortingChange: true,
collapseOnPageChange: true,
collapseOnDataChange: true,
freezeWhenExpanded: false,
filterable: false,
sortable: true,
resizable: true
},
data: data
}
this.setTableOption = this.setTableOption.bind(this)
}
render () {
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName'
}, {
Header: 'Last Name',
id: 'lastName',
accessor: d => d.lastName
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div>
<h1>Table Options</h1>
<table>
<tbody>
{
Object.keys(this.state.tableOptions).map(optionKey => {
const optionValue = this.state.tableOptions[optionKey]
return (
<tr key={optionKey}>
<td>{optionKey}</td>
<td style={{paddingLeft: 10, paddingTop: 5}}>
<input type='checkbox'
name={optionKey}
checked={optionValue}
onChange={this.setTableOption}
/>
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={this.state.data}
columns={columns}
defaultPageSize={10}
{...this.state.tableOptions}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>You can put any component you want here, even another React Table!</em>
<br />
<br />
<ReactTable
data={this.state.data}
columns={columns}
defaultPageSize={3}
showPagination={false}
SubComponent={(row) => {
return (
<div style={{padding: '20px'}}>
<em>It even has access to the row data: </em>
<CodeHighlight>{() => JSON.stringify(row, null, 2)}</CodeHighlight>
</div>
)
}}
/>
</div>
)
}}
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
setTableOption (event) {
const target = event.target
const value = target.type === 'checkbox' ? target.checked : target.value
const name = target.name
this.setState({
tableOptions: {
...this.state.tableOptions,
[name]: value
}
})
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./SubComponents')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
-78
View File
@@ -1,78 +0,0 @@
/* eslint-disable import/no-webpack-loader-syntax */
import React from 'react'
import _ from 'lodash'
import namor from 'namor'
import ReactTable from '../../../lib/index'
class Story extends React.PureComponent {
render () {
const data = _.map(_.range(5553), d => {
const children = _.map(_.range(10), d => {
const grandChildren = _.map(_.range(10), d => {
return {
age: Math.floor(Math.random() * 30)
}
})
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
children: grandChildren
}
})
return {
lastName: namor.generate({ words: 1, numbers: 0 }),
firstName: children.map(d => d.firstName),
age: Math.floor(Math.random() * 30),
children
}
})
const columns = [{
Header: 'Name',
columns: [{
Header: 'First Name',
accessor: 'firstName',
expander: true
}, {
Header: 'Last Name',
accessor: 'lastName'
}]
}, {
Header: 'Info',
columns: [{
Header: 'Age',
accessor: 'age'
}]
}]
return (
<div>
<div className='table-wrap'>
<ReactTable
className='-striped -highlight'
data={data}
columns={columns}
defaultPageSize={10}
subRowsKey='children'
/>
</div>
<div style={{textAlign: 'center'}}>
<br />
<em>Tip: Hold shift when sorting to multi-sort!</em>
</div>
</div>
)
}
}
// Source Code
const CodeHighlight = require('./components/codeHighlight').default
const source = require('!raw!./SubRows')
export default () => (
<div>
<Story />
<CodeHighlight>{() => source}</CodeHighlight>
</div>
)
@@ -1,21 +0,0 @@
import React from 'react'
import '../utils/prism'
export default class CodeHighlight extends React.Component {
render () {
const { language, children } = this.props
return (
<pre>
<code className={'language-' + (language || 'jsx')}>
{children()}
</code>
</pre>
)
}
componentDidMount () {
window.Prism.highlightAll()
}
componentDidUpdate () {
window.Prism.highlightAll()
}
}
+27
View File
@@ -0,0 +1,27 @@
import React from "react";
import ReactTable from "../../../lib/index";
import "../../../react-table.css";
const data = [
{ one: "1.1", two: "1.2" },
{ one: "2.1", two: "2.2" },
{ one: "3.1", two: "3.2" },
{ one: "4.1", two: "4.2" }
];
const columns = [
{ accessor: "one", Header: "One" },
{ accessor: "two", Header: "Two" }
];
export default class Story extends React.Component {
render() {
return (
<div>
Test
<ReactTable data={data} columns={columns} />
</div>
);
}
}
File diff suppressed because one or more lines are too long
+1944 -424
View File
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

+8348
View File
File diff suppressed because it is too large Load Diff
+94 -40
View File
@@ -1,12 +1,12 @@
{
"name": "react-table",
"version": "6.2.0",
"version": "6.9.0",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
"homepage": "https://github.com/react-tools/react-table#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/tannerlinsley/react-table.git"
"url": "git+https://github.com/react-tools/react-table.git"
},
"keywords": [
"react",
@@ -15,69 +15,123 @@
"datagrid"
],
"main": "lib/index.js",
"module": "es/index.js",
"files": [
"src/",
"es/",
"lib/",
"react-table.js",
"react-table.min.js",
"react-table.css",
"media/*.png"
],
"scripts": {
"build:node": "babel src --out-dir lib --source-maps inline",
"build:css": "rimraf react-table.css && stylus src/index.styl --compress -o react-table.css && yarn run css:autoprefix",
"build:cjs": "babel src --out-dir lib --source-maps inline --copy-files",
"build:es": "cross-env BABEL_ENV=es babel src --out-dir es --source-maps inline",
"build:umd": "cross-env BABEL_ENV=umd rollup -c",
"build:umd-min": "cross-env BABEL_ENV=umd NODE_ENV=production rollup -c",
"build:css": "rimraf react-table.css && stylus src/index.styl --compress -o react-table.css && yarn css:autoprefix",
"css:autoprefix": "postcss --use autoprefixer react-table.css -r",
"watch": "npm-run-all --parallel watch:*",
"watch:node": "onchange 'src/**/*.js' -i -- npm run build:node",
"watch:css": "onchange 'src/**/*.styl' -i -- npm run build:css",
"test": "standard",
"umd": "rimraf react-table.js && webpack --config umd.webpack.js",
"watch:js": "onchange 'src/**/*.js' -i -- yarn build:cjs",
"watch:css": "onchange 'src/**/*.styl' -i -- yarn build:css",
"test": "eslint src",
"build": "npm-run-all build:*",
"prepublish": "npm run build && npm run umd",
"prepublish": "yarn build",
"postpublish": "git push --tags",
"docs": "cd docs && yarn && yarn start",
"docs:build": "cd docs && yarn && yarn run build"
"docs": "yarn watch & cd docs && yarn && yarn start",
"docs:build": "yarn build && cd docs && yarn && yarn build"
},
"dependencies": {
"classnames": "^2.2.5",
"react-json-tree": "^0.10.9"
"classnames": "^2.2.5"
},
"peerDependencies": {
"react": "^15.x.x"
"prop-types": "^15.5.0",
"react": "^15.x.x || ^16.x.x",
"react-dom": "^15.x.x || ^16.x.x"
},
"devDependencies": {
"autoprefixer": "^6.7.0",
"babel-cli": "6.14.0",
"babel-eslint": "6.1.2",
"babel-preset-es2015": "6.14.0",
"babel-preset-react": "6.11.1",
"babel-preset-stage-2": "6.13.0",
"npm-run-all": "^3.1.1",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"cross-env": "^5.1.4",
"eslint": "^4.1.1",
"eslint-config-react-tools": "^1.0.10",
"eslint-plugin-class-property": "^1.0.6",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.4.0",
"match-sorter": "^1.8.0",
"npm-run-all": "^4.1.2",
"onchange": "^3.0.2",
"postcss-cli": "^2.6.0",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"prop-types": "^15.6.0",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-json-tree": "^0.10.9",
"rimraf": "^2.6.1",
"rollup": "^0.55.3",
"rollup-plugin-babel": "^3.0.3",
"rollup-plugin-commonjs": "^8.3.0",
"rollup-plugin-node-resolve": "^3.0.2",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-uglify": "^3.0.0",
"standard": "^10.0.2",
"stylus": "^0.54.5",
"webpack": "^2.5.1"
},
"standard": {
"parser": "babel-eslint",
"ignore": [
"node_modules",
"dist",
"lib",
"example",
"react-table.js",
"stories",
"docs"
]
"stylus": "^0.54.5"
},
"babel": {
"presets": [
"es2015",
"stage-2",
"react"
]
"env": {
"development": {
"presets": [
[
"env",
{
"modules": "commonjs"
}
],
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties"
]
},
"es": {
"presets": [
[
"env",
{
"modules": false
}
],
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties"
]
},
"umd": {
"presets": [
[
"env",
{
"modules": false
}
],
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"external-helpers"
]
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
import nodeResolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
import replace from 'rollup-plugin-replace'
import commonjs from 'rollup-plugin-commonjs'
import uglify from 'rollup-plugin-uglify'
const env = process.env.NODE_ENV
const config = {
input: 'src/index.js',
output: {
file: env === 'production' ? 'react-table.min.js' : 'react-table.js',
format: 'umd',
globals: {
react: 'React',
},
name: 'ReactTable',
exports: 'named',
},
external: ['react'],
plugins: [
nodeResolve(),
babel({
exclude: '**/node_modules/**',
}),
replace({
'process.env.NODE_ENV': JSON.stringify(env),
}),
commonjs(),
],
}
if (env === 'production') {
config.plugins.push(uglify({
compress: {
dead_code: true,
warnings: false,
},
}))
}
export default config
+95 -62
View File
@@ -9,12 +9,14 @@ const emptyObj = () => ({})
export default {
// General
data: [],
resolveData: data => data,
loading: false,
showPagination: true,
showPaginationTop: false,
showPaginationBottom: true,
showPageSizeOptions: true,
pageSizeOptions: [5, 10, 20, 25, 50, 100],
defaultPage: 0,
defaultPageSize: 20,
showPageJump: true,
collapseOnSortingChange: true,
@@ -22,20 +24,24 @@ export default {
collapseOnDataChange: true,
freezeWhenExpanded: false,
sortable: true,
multiSort: true,
resizable: true,
filterable: false,
defaultSortDesc: false,
defaultSorted: [],
defaultFiltered: [],
defaultResized: [],
defaultExpanded: {},
// eslint-disable-next-line no-unused-vars
defaultFilterMethod: (filter, row, column) => {
const id = filter.pivotId || filter.id
return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true
},
defaultSortMethod: (a, b) => {
// eslint-disable-next-line no-unused-vars
defaultSortMethod: (a, b, desc) => {
// force null and undefined to the bottom
a = (a === null || a === undefined) ? '' : a
b = (b === null || b === undefined) ? '' : b
a = a === null || a === undefined ? '' : a
b = b === null || b === undefined ? '' : b
// force any string values to lowercase
a = typeof a === 'string' ? a.toLowerCase() : a
b = typeof b === 'string' ? b.toLowerCase() : b
@@ -46,7 +52,8 @@ export default {
if (a < b) {
return -1
}
// returning 0, undefined or any falsey value will use subsequent sorts or the index as a tiebreaker
// returning 0, undefined or any falsey value will use subsequent sorts or
// the index as a tiebreaker
return 0
},
@@ -121,12 +128,14 @@ export default {
PivotValue: undefined,
Expander: undefined,
Filter: undefined,
Placeholder: undefined,
// All Columns
sortable: undefined, // use table default
resizable: undefined, // use table default
filterable: undefined, // use table default
show: true,
minWidth: 100,
minResizeWidth: 11,
// Cells only
className: '',
style: {},
@@ -142,7 +151,8 @@ export default {
footerStyle: {},
getFooterProps: emptyObj,
filterMethod: undefined,
sortMethod: undefined
filterAll: false,
sortMethod: undefined,
},
// Global Expander Column Defaults
@@ -150,7 +160,7 @@ export default {
sortable: false,
resizable: false,
filterable: false,
width: 35
width: 35,
},
pivotDefaults: {
@@ -165,73 +175,96 @@ export default {
pageText: 'Page',
ofText: 'of',
rowsText: 'rows',
pageJumpText: 'jump to page',
rowsSelectorText: 'rows per page',
// Components
TableComponent: _.makeTemplateComponent('rt-table'),
TheadComponent: _.makeTemplateComponent('rt-thead'),
TbodyComponent: _.makeTemplateComponent('rt-tbody'),
TrGroupComponent: _.makeTemplateComponent('rt-tr-group'),
TrComponent: _.makeTemplateComponent('rt-tr'),
ThComponent: ({toggleSort, className, children, ...rest}) => {
return (
<div
className={classnames(className, 'rt-th')}
onClick={e => {
toggleSort && toggleSort(e)
}}
{...rest}
>
{children}
</div>
)
},
TdComponent: _.makeTemplateComponent('rt-td'),
TfootComponent: _.makeTemplateComponent('rt-tfoot'),
FilterComponent: ({filter, onChange}) => (
<input type='text'
style={{
width: '100%'
}}
value={filter ? filter.value : ''}
onChange={(event) => onChange(event.target.value)}
/>
),
ExpanderComponent: ({isExpanded}) => (
<div className={classnames('rt-expander', isExpanded && '-open')}>
&bull;
TableComponent: ({ children, className, ...rest }) => (
<div
className={classnames('rt-table', className)}
role="grid"
// tabIndex='0'
{...rest}
>
{children}
</div>
),
PivotValueComponent: ({subRows, value}) => (
<span>{value} {subRows && `(${subRows.length})`}</span>
TheadComponent: _.makeTemplateComponent('rt-thead', 'Thead'),
TbodyComponent: _.makeTemplateComponent('rt-tbody', 'Tbody'),
TrGroupComponent: ({ children, className, ...rest }) => (
<div className={classnames('rt-tr-group', className)} role="rowgroup" {...rest}>
{children}
</div>
),
AggregatedComponent: ({subRows, column}) => {
const previewValues = subRows
.filter(d => typeof d[column.id] !== 'undefined')
.map((row, i) => (
<span key={i}>{row[column.id]}{i < subRows.length - 1 ? ', ' : ''}</span>
))
return (
<span>{previewValues}</span>
)
TrComponent: ({ children, className, ...rest }) => (
<div className={classnames('rt-tr', className)} role="row" {...rest}>
{children}
</div>
),
ThComponent: ({
toggleSort, className, children, ...rest
}) => (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events
<div
className={classnames('rt-th', className)}
onClick={e => toggleSort && toggleSort(e)}
role="columnheader"
tabIndex="-1" // Resolves eslint issues without implementing keyboard navigation incorrectly
{...rest}
>
{children}
</div>
),
TdComponent: ({
toggleSort, className, children, ...rest
}) => (
<div className={classnames('rt-td', className)} role="gridcell" {...rest}>
{children}
</div>
),
TfootComponent: _.makeTemplateComponent('rt-tfoot', 'Tfoot'),
FilterComponent: ({ filter, onChange, column }) => (
<input
type="text"
style={{
width: '100%',
}}
placeholder={column.Placeholder}
value={filter ? filter.value : ''}
onChange={event => onChange(event.target.value)}
/>
),
ExpanderComponent: ({ isExpanded }) => (
<div className={classnames('rt-expander', isExpanded && '-open')}>&bull;</div>
),
PivotValueComponent: ({ subRows, value }) => (
<span>
{value} {subRows && `(${subRows.length})`}
</span>
),
AggregatedComponent: ({ subRows, column }) => {
const previewValues = subRows.filter(d => typeof d[column.id] !== 'undefined').map((row, i) => (
// eslint-disable-next-line react/no-array-index-key
<span key={i}>
{row[column.id]}
{i < subRows.length - 1 ? ', ' : ''}
</span>
))
return <span>{previewValues}</span>
},
PivotComponent: undefined, // this is a computed default generated using
// the ExpanderComponent and PivotValueComponent at run-time in methods.js
PaginationComponent: Pagination,
PreviousComponent: undefined,
NextComponent: undefined,
LoadingComponent: ({className, loading, loadingText, ...rest}) => (
<div className={classnames(
'-loading',
{'-active': loading},
className
)}
{...rest}
>
<div className='-loading-inner'>
{loadingText}
</div>
LoadingComponent: ({
className, loading, loadingText, ...rest
}) => (
<div className={classnames('-loading', { '-active': loading }, className)} {...rest}>
<div className="-loading-inner">{loadingText}</div>
</div>
),
NoDataComponent: _.makeTemplateComponent('rt-noData'),
ResizerComponent: _.makeTemplateComponent('rt-resizer')
NoDataComponent: _.makeTemplateComponent('rt-noData', 'NoData'),
ResizerComponent: _.makeTemplateComponent('rt-resizer', 'Resizer'),
PadRowComponent: () => <span>&nbsp;</span>,
}
+316
View File
@@ -0,0 +1,316 @@
<div style="text-align:center;">
<a href="https://github.com/react-tools/react-table" target="\_parent"><img src="https://github.com/react-tools/media/raw/master/logo-react-table.png" alt="React Table Logo" style="width:450px;"/></a>
</div>
# ReactTable - expanding with HOCs
This documentation is about expanding ReactTable using Higher Order Components/Functions.
## Covered in this README
* A Brief explanation of HOCs and why they are a good approach for ReactTable enhancements
* Documentation of the currently available HOCs
* TreeTable
* SelectTable
* Documentation of the standard for writing HOCs with ReactTable
## What are HOCs and why use them with ReactTable
HOCs (or Higher Order Components/Functions) are either a React Component (or a function that returns a React Component)
that are used to enhance the functionality of an existing component. How much you can enhance depends on the props that
the component exposes.
Fortunately, ReactTable exposes a LOT of functionality as props to the component. In some cases there are too many
props to keep track of and that is where HOCs come in.
You can write a HOC that just focusses on the additional functionality you want to enhance and keep those enhancements to
reuse over and over again when you need them. You don't have to edit the ReactSource code, just wrap ReactTable in one or
more HOCs (more on some issues related to chaining HOCs later) that provide the additional functionality you want to expose.
The most obvious HOC is one that can add `checkbox` or select functionality. The HOC included provides `select` functionality
that allows the developer to specify if they want a `checkbox` or `radio` style of select column. The implementation of the
selection is recorded (e.g. in component state, Redux, etc.) and how to manage multiple selections. The HOC really only handles
the rendering pieces.
But there is more documentation on the `select` HOC below.
## Currently Available HOCs
Any of the below HOCs can be imported from react-table like so:
```javascript
import ReactTable from "react-table";
import treeTableHOC from "react-table/lib/hoc/treeTable";
const TreeTable = treeTableHOC(ReactTable);
```
Swap `treeTable` and `TreeTable` with any of the other HOC names as necessary.
### TreeTable
TreeTable takes over the rendering of the generated pivot rows of ReactTable so that they appear more like an expandable Tree.
It accomplishes this by rendering a 100% wide div and then only rendering the cell that controls the pivot at that level.
Using it is as simple as doing the following:
```javascript
const TreeTable = treeTableHOC(ReactTable);
```
After you have done the above, you can then use `TreeTable` just as you would `ReactTable` but it will render pivots using
the Tree style described above.
### SelectTable
SelectTable is a little trickier. The HOCs attempt to avoid adding additional state and, as there is no internal ID for a row that
can be relied on to be static (ReactTable just reuses indexes when rendering) the developer has to maintain the state outside of even
the wrapped component. So it is largely based on callbacks.
You include the HOC in the same manner as you would for the treeTableHOC but then need to provide the following overrides:
* isSelected - returns `true` if the key passed is selected otherwise it should return `false`
* selectAll - a property that indicates if the selectAll is set (`true|false`)
* toggleAll - called when the user clicks the `selectAll` checkbox/radio
* toggleSelection - called when the use clicks a specific checkbox/radio in a row
* selectType - either `checkbox|radio` to indicate what type of selection is required
**Note:** The select field defaults to the accessor `_id` property in order to render the select field for that particular row. If your objects have different
unique ID fields, make sure to tell React Table that by passing it the `keyField` property.
```javascript
<ReactTable keyField='id' />
```
In the case of `radio` there is no `selectAll` displayed but the developer is responsible for only making one selection in
the controlling component's state. You could select multiple but it wouldn't make sense and you should use `checkbox` instead.
You also have to decide what `selectAll` means. Given ReactTable is a paged solution there are other records off-page. When someone
selects the `selectAll` checkbox, should it mark every possible record, only what might be visible to due a Filter or only those items
on the current page?
The example opts for the middle approach so it gets a `ref` to the ReactTable instance and pulls the `sortedData` out of the resolved
state (then walks through those records and pulls their ID into the `selection` state of the controlling component).
You can also replace the input component that is used to render the select box and select all box:
* SelectAllInputComponent - the checkbox in the top left corner
* SelectInputComponent - the checkbox used on a row
### SelectTreeTable
SelectTreeTable is a combination of TreeTable and SelectTable.
To function correctly the chain has to be in the correct order as follows (see the comments in the guid on HOCs below).
```javascript
const SelectTreeTable = selectTableHOC(treeTableHOC(ReactTable));
```
In this particular instance it is (probably) because the functions need access to the state on the wrapped component to manage
the selected items. Although that is not totally clearly the issue.
### FoldableTable
FoldableTable is a HOC that make the columns are foldable. The reason I developed this HOC because when working on the real project related to the financial which display so many columns for validation and comparison.
So foldable columns allow users to temporary hidden the unwanted to columns so that they can focus on the data that they want to see.
#### How it works
```javascript
const FoldableTable = FoldableTableHOC(ReactTable);
```
It will scan all the columns which `foldable` is `true` and apply the foldable column feature. This feature will work for both normal columns and header columns as samples below.
- With Header Columns
```javascript
render(){
return <FoldableTable
columns={[{
Header: "Name",
foldable: true,
columns: [{
Header: "First Name",
accessor: "first_name"
},{
Header: "Last Name",
accessor: "last_name"
}]
},{
Header: "Info",
foldable: true,
columns: [{
Header: "Email",
accessor: "email"
},{
Header: "Gender",
accessor: "gender"
}]
}]
}/>
}
```
![With Header Columns](https://raw.githubusercontent.com/baoduy/Images/master/Wordpress/JavaScripts/react-table%20foldableHOC/FoldableTable%20With%20Header.gif)
- With Nornal Columns
```javascript
render() {
return <FoldableTable
columns={[{
Header: "First Name",
accessor: "first_name"
},
{
Header: "Last Name",
accessor: "last_name",
foldable: true,
},
{
Header: "Email",
accessor: "email",
foldable: true,
},
{
Header: "Gender",
accessor: "gender",
foldable: true,
}]}></FoldableTable>
}
```
![With Normal Columns](https://raw.githubusercontent.com/baoduy/Images/master/Wordpress/JavaScripts/react-table%20foldableHOC/FoldableTable%20Without%20Header.gif)
- The `FoldableTable` also fully compatible with existing HOCs, below is with selectTableHOC.
![With Normal Columns](https://raw.githubusercontent.com/baoduy/Images/master/Wordpress/JavaScripts/react-table%20foldableHOC/FoldableTable%20With%20selectTable.gif)
#### State management
If you would like to manage the state of FoldableTable, then add the following codes.
```javascript
render() {
return <FoldableTable
onFoldChange={newFolded => this.setState(p => { return { folded: newFolded } })}
folded={this.state.folded}
/>
}
```
#### Custom Components
- FoldIconComponent: to render the Icon of buttons.
- FoldButtonComponent: to render the folding buttons for each Column.
With default rendering as below.
```javascript
const defaultFoldIconComponent = ({ collapsed }) => {
//Render your Icon here
}
const defaultFoldButtonComponent = ({ header, collapsed, icon, onClick }) => {
//Render your button here.
}
```
### AdvancedExpandTable
HOC which allows any Cell in the row to toggle the row's
SubComponent (expand/collapse). Also allows the SubComponent to toggle itself. Technically supports toggling any row's SubComponent.
These are the expand functions available to any SubComponent or Column Cell:
```
toggleRowSubComponent
showRowSubComponent
hideRowSubComponent
```
They are available through the `props.columnProps.rest` object.
On any change to the props, the table will reset the expanded state.
Accepts a onExpandedChange callback to be called whenever the table expanded state changes
Note: only supports 1 level of nesting.
Example usage in a Column Cell Renderer:
```javascript
Cell: props => {
const {
value
columnProps: { rest: { showRowSubComponent } },
nestingPath
} = props;
return (
<div>
<button
onClick={e => showRowSubComponent(nestingPath, e)}
>
{value}
</button>
</div>
);
}
```
Example usage in the ReactTable SubComponent (toggle itself):
```javascript
const AdvancedExpandReactTable = advancedExpandTableHOC(ReactTable);
<AdvancedExpandReactTable>
...
SubComponent={({ row, nestingPath, toggleRowSubComponent }) => {
return (
<div>
<button
onClick={e => toggleRowSubComponent({ nestingPath }, e)}
>
{row.value}
</button>
</div>
);
}}
/>
```
Each Column Renderer (E.g. Cell ) gets the expand functions in its props and each SubComponent gets the expand functions in its props
Expand functions takes the `nestingPath` or `rowInfo` given to each
Column Renderer and SubComponent already by ReactTable.
## HOC Guide for ReactTable
There are a few rules required when writing a HOC for ReactTable (other than meeting the normal lint standards - which are
still being developed).
Firstly, there are issues with `ref` when you write a HOC. Consider a deeply nested component wrapped in multiple HOCs...
A HOC in the middle of the chain requires access to the instance of the component it thinks it is wrapping but there is at
least one other wrapper in the way. The challenge is: How do I get to the actual wrapped component?
Each HOC is required to be a React Class so that a `ref` can be obtained against each component:
```Javascript
<Component ... ref={r => this.wrappedInstance = r} />
```
_NOTE:_ "Component" can also be the `<ReactTable />` instance.
Then the following method needs
to be placed on the class so that it exposes the correct instance of ReactTable:
```Javascript
getWrappedInstance() {
if (!this.wrappedInstance) console.warn('<component name here> - No wrapped instance')
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
else return this.wrappedInstance
}
```
Essentially this will walk down the chain (if there are chained HOCs) and stop when it gets to the end and return the wrapped instance.
Finally, sometimes the chains need to be in a specific order to function correctly. It is not clear if this is just an architectural
issue or if it would be better solved using a library like `recompose`. Anyone who is able to contribute a reliable solution to this
is welcome to submit a PR.
+199
View File
@@ -0,0 +1,199 @@
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import set from 'lodash.set'
import get from 'lodash.get'
/*
AvancedExpandTableHOC for ReactTable
HOC which allows any Cell in the row to toggle the row's
SubComponent. Also allows the SubComponent to toggle itself.
Expand functions available to any SubComponent or Column Cell:
toggleRowSubComponent
showRowSubComponent
hideRowSubComponent
Each Column Renderer (E.g. Cell ) gets the expand functions in its props
And Each SubComponent gets the expand functions in its props
Expand functions takes the `rowInfo` given to each
Column Renderer and SubComponent already by ReactTable.
*/
export const subComponentWithToggle = (SubComponent, expandFuncs) => props => (
<SubComponent {...props} {...expandFuncs} />
)
// each cell in the column gets passed the function to toggle a sub component
export const columnsWithToggle = (columns, expandFuncs) =>
columns.map(column => {
if (column.columns) {
return {
...column,
columns: columnsWithToggle(column.columns, expandFuncs),
}
}
return {
...column,
getProps () {
return {
...expandFuncs,
}
},
}
})
export const advancedExpandTableHOC = TableComponent =>
class AdvancedExpandTable extends Component {
constructor (props) {
super(props)
this.state = {
expanded: {},
}
this.toggleRowSubComponent = this.toggleRowSubComponent.bind(this)
this.showRowSubComponent = this.showRowSubComponent.bind(this)
this.hideRowSubComponent = this.hideRowSubComponent.bind(this)
this.getTdProps = this.getTdProps.bind(this)
this.fireOnExpandedChange = this.fireOnExpandedChange.bind(this)
this.expandFuncs = {
toggleRowSubComponent: this.toggleRowSubComponent,
showRowSubComponent: this.showRowSubComponent,
hideRowSubComponent: this.hideRowSubComponent,
}
}
// after initial render if we get new
// data, columns, page changes, etc.
// we reset expanded state.
componentWillReceiveProps () {
this.setState({
expanded: {},
})
}
static propTypes = {
columns: PropTypes.array.isRequired,
SubComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element])
.isRequired,
onExpandedChange: PropTypes.func,
};
static defaultProps = {
onExpandedChange: null,
};
static DisplayName = 'AdvancedExpandTable';
// since we pass the expand functions to each Cell,
// we need to filter it out from being passed as an
// actual DOM attribute. See getProps in columnsWithToggle above.
static TdComponent ({
toggleRowSubComponent,
showRowSubComponent,
hideRowSubComponent,
...rest
}) {
return <TableComponent.defaultProps.TdComponent {...rest} />
}
fireOnExpandedChange (rowInfo, e) {
// fire callback once state has changed.
if (this.props.onExpandedChange) {
this.props.onExpandedChange(rowInfo, e)
}
}
resolveNewTableState (rowInfoOrNestingPath, e, expandType) {
// derive nestingPath if only rowInfo is passed
let nestingPath = rowInfoOrNestingPath
if (rowInfoOrNestingPath.nestingPath) {
nestingPath = rowInfoOrNestingPath.nestingPath
}
this.setState(
prevState => {
const isExpanded = get(prevState.expanded, nestingPath)
// since we do not support nested rows, a shallow clone is okay.
const newExpanded = { ...prevState.expanded }
switch (expandType) {
case 'show':
set(newExpanded, nestingPath, {})
break
case 'hide':
set(newExpanded, nestingPath, false)
break
default:
// toggle
set(newExpanded, nestingPath, isExpanded ? false : {})
}
return {
...prevState,
expanded: newExpanded,
}
},
() => this.fireOnExpandedChange(rowInfoOrNestingPath, e)
)
}
toggleRowSubComponent (rowInfo, e) {
this.resolveNewTableState(rowInfo, e)
}
showRowSubComponent (rowInfo, e) {
this.resolveNewTableState(rowInfo, e, 'show')
}
hideRowSubComponent (rowInfo, e) {
this.resolveNewTableState(rowInfo, e, 'hide')
}
getTdProps (tableState, rowInfo, column) {
const { expander } = column
if (!expander) {
// no overrides
return {}
}
return {
// only override onClick for column Td
onClick: e => {
this.toggleRowSubComponent(rowInfo, e)
},
}
}
getWrappedInstance () {
if (!this.wrappedInstance) { console.warn('AdvancedExpandTable - No wrapped instance') }
if (this.wrappedInstance.getWrappedInstance) {
return this.wrappedInstance.getWrappedInstance()
}
return this.wrappedInstance
}
render () {
const {
columns, SubComponent, onExpandedChange, ...rest
} = this.props
const wrappedColumns = columnsWithToggle(columns, this.expandFuncs)
const WrappedSubComponent = subComponentWithToggle(
SubComponent,
this.expandFuncs
)
return (
<TableComponent
{...rest}
columns={wrappedColumns}
expanded={this.state.expanded}
getTdProps={this.getTdProps}
SubComponent={WrappedSubComponent}
TdComponent={AdvancedExpandTable.TdComponent}
/>
)
}
}
+230
View File
@@ -0,0 +1,230 @@
/* eslint-disable */
import React from 'react'
import left from './left.svg'
import right from './right.svg'
const defaultFoldIconComponent = ({ collapsed }) => {
const style = { width: 25 }
if (collapsed) return <img src={right} style={style} alt="right" />
return <img src={left} style={style} alt="left" />
}
const defaultFoldButtonComponent = ({ header, collapsed, icon, onClick }) => {
const style = {
marginLeft: '0px',
marginTop: '-5px',
marginBottom: '-8px',
float: 'left',
cursor: 'pointer',
}
return (
<div>
<div style={style} onClick={onClick}>
{icon}
</div>
{!collapsed && <div>{header}</div>}
</div>
)
}
export default ReactTable => {
const wrapper = class RTFoldableTable extends React.Component {
constructor(props, context) {
super(props, context)
this.state = {
folded: props.onFoldChange ? undefined : {},
resized: props.resized || [],
}
}
componentWillReceiveProps(newProps) {
if (this.state.resized !== newProps.resized) {
this.setState(p => ({ resized: newProps.resized }))
}
}
onResizedChange = resized => {
const { onResizedChange } = this.props
if (onResizedChange) onResizedChange(resized)
else {
this.setState(p => ({ resized }))
}
}
removeResized = column => {
const { id } = column
if (!id) return
const { resized } = this.state
if (!resized) return
const rs = resized.find(r => r.id === id)
if (!rs) return
const newResized = resized.filter(r => r !== rs)
this.onResizedChange(newResized)
}
// this is so we can expose the underlying ReactTable.
getWrappedInstance = () => {
if (!this.wrappedInstance) console.warn('RTFoldableTable - No wrapped instance')
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
return this.wrappedInstance
}
getCopiedKey = key => {
const { foldableOriginalKey } = this.props
return `${foldableOriginalKey}${key}`
}
copyOriginals = column => {
const { FoldedColumn } = this.props
// Stop copy if the column already copied
if (column.original_Header) return
Object.keys(FoldedColumn).forEach(k => {
const copiedKey = this.getCopiedKey(k)
if (k === 'Cell') column[copiedKey] = column[k] ? column[k] : c => c.value
else column[copiedKey] = column[k]
})
// Copy sub Columns
if (column.columns && !column.original_Columns) column.original_Columns = column.columns
// Copy Header
if (!column.original_Header) column.original_Header = column.Header
}
restoreToOriginal = column => {
const { FoldedColumn } = this.props
Object.keys(FoldedColumn).forEach(k => {
// ignore header as handling by foldableHeaderRender
if (k === 'Header') return
const copiedKey = this.getCopiedKey(k)
column[k] = column[copiedKey]
})
if (column.columns && column.original_Columns) column.columns = column.original_Columns
}
getState = () => (this.props.onFoldChange ? this.props.folded : this.state.folded)
isFolded = col => {
const folded = this.getState()
return folded[col.id] === true
}
foldingHandler = col => {
if (!col || !col.id) return
const { onFoldChange } = this.props
const folded = this.getState()
const { id } = col
const newFold = Object.assign({}, folded)
newFold[id] = !newFold[id]
// Remove the Resized if have
this.removeResized(col)
if (onFoldChange) onFoldChange(newFold)
else {
this.setState(previous => ({ folded: newFold }))
}
}
foldableHeaderRender = cell => {
const { FoldButtonComponent, FoldIconComponent } = this.props
const { column } = cell
const collapsed = this.isFolded(column)
const icon = React.createElement(FoldIconComponent, { collapsed })
const onClick = () => this.foldingHandler(column)
return React.createElement(FoldButtonComponent, {
header: column.original_Header,
collapsed,
icon,
onClick,
})
}
applyFoldableForColumn = column => {
const collapsed = this.isFolded(column)
const { FoldedColumn } = this.props
// Handle Column Header
if (column.columns) {
if (collapsed) {
column.columns = [FoldedColumn]
column.width = FoldedColumn.width
column.style = FoldedColumn.style
} else this.restoreToOriginal(column)
}
// Handle Normal Column.
else if (collapsed) column = Object.assign(column, FoldedColumn)
else {
this.restoreToOriginal(column)
}
}
applyFoldableForColumns = columns =>
columns.map((col, index) => {
if (!col.foldable) return col
// If col don't have id then generate id based on index
if (!col.id) col.id = `col_${index}`
this.copyOriginals(col)
// Replace current header with internal header render.
col.Header = c => this.foldableHeaderRender(c)
// apply foldable
this.applyFoldableForColumn(col)
// return the new column out
return col
})
render() {
const {
columns: originalCols,
FoldButtonComponent,
FoldIconComponent,
FoldedColumn,
...rest
} = this.props
const columns = this.applyFoldableForColumns([...originalCols])
const extra = {
columns,
onResizedChange: this.onResizedChange,
resized: this.state.resized,
}
return <ReactTable {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
}
}
wrapper.displayName = 'RTFoldableTable'
wrapper.defaultProps = {
FoldIconComponent: defaultFoldIconComponent,
FoldButtonComponent: defaultFoldButtonComponent,
foldableOriginalKey: 'original_',
FoldedColumn: {
Cell: c => '',
width: 30,
sortable: false,
resizable: false,
filterable: false,
},
}
return wrapper
}
+1
View File
@@ -0,0 +1 @@
<?xml version="1.0" ?><!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'><svg height="512px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M327.3,98.9l-2.1,1.8l-156.5,136c-5.3,4.6-8.6,11.5-8.6,19.2c0,7.7,3.4,14.6,8.6,19.2L324.9,411l2.6,2.3 c2.5,1.7,5.5,2.7,8.7,2.7c8.7,0,15.8-7.4,15.8-16.6h0V112.6h0c0-9.2-7.1-16.6-15.8-16.6C332.9,96,329.8,97.1,327.3,98.9z"/></svg>

After

Width:  |  Height:  |  Size: 583 B

+1
View File
@@ -0,0 +1 @@
<?xml version="1.0" ?><!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'><svg height="512px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="512px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M184.7,413.1l2.1-1.8l156.5-136c5.3-4.6,8.6-11.5,8.6-19.2c0-7.7-3.4-14.6-8.6-19.2L187.1,101l-2.6-2.3 C182,97,179,96,175.8,96c-8.7,0-15.8,7.4-15.8,16.6h0v286.8h0c0,9.2,7.1,16.6,15.8,16.6C179.1,416,182.2,414.9,184.7,413.1z"/></svg>

After

Width:  |  Height:  |  Size: 585 B

+119
View File
@@ -0,0 +1,119 @@
/* eslint-disable */
import React from 'react'
const defaultSelectInputComponent = props => {
return (
<input
type={props.selectType || 'checkbox'}
aria-label={`${props.checked ? 'Un-select':'Select'} row with id:${props.id}` }
checked={props.checked}
id={props.id}
onClick={e => {
const { shiftKey } = e
e.stopPropagation()
props.onClick(props.id, shiftKey, props.row)
}}
onChange={() => {}}
/>
)
}
export default (Component, options) => {
const wrapper = class RTSelectTable extends React.Component {
constructor(props) {
super(props)
}
rowSelector(row) {
if (!row || !row.hasOwnProperty(this.props.keyField)) return null
const { toggleSelection, selectType, keyField } = this.props
const checked = this.props.isSelected(row[this.props.keyField])
const inputProps = {
checked,
onClick: toggleSelection,
selectType,
row,
id: `select-${row[keyField]}`
}
return React.createElement(this.props.SelectInputComponent, inputProps)
}
headSelector(row) {
const { selectType } = this.props
if (selectType === 'radio') return null
const { toggleAll, selectAll: checked, SelectAllInputComponent } = this.props
const inputProps = {
checked,
onClick: toggleAll,
selectType,
id: 'select-all'
}
return React.createElement(SelectAllInputComponent, inputProps)
}
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
getWrappedInstance() {
if (!this.wrappedInstance) console.warn('RTSelectTable - No wrapped instance')
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
else return this.wrappedInstance
}
render() {
const {
columns: originalCols,
isSelected,
toggleSelection,
toggleAll,
keyField,
selectAll,
selectType,
selectWidth,
SelectAllInputComponent,
SelectInputComponent,
...rest
} = this.props
const select = {
id: '_selector',
accessor: () => 'x', // this value is not important
Header: this.headSelector.bind(this),
Cell: ci => {
return this.rowSelector.bind(this)(ci.original)
},
width: selectWidth || 30,
filterable: false,
sortable: false,
resizable: false,
style: { textAlign: 'center' },
}
const columns = (options !== undefined && options.floatingLeft === true) ? [...originalCols, select] : [select, ...originalCols]
const extra = {
columns,
}
return <Component {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
}
}
wrapper.displayName = 'RTSelectTable'
wrapper.defaultProps = {
keyField: '_id',
isSelected: key => {
console.log('No isSelected handler provided:', { key })
},
selectAll: false,
toggleSelection: (key, shift, row) => {
console.log('No toggleSelection handler provided:', { key, shift, row })
},
toggleAll: () => {
console.log('No toggleAll handler provided.')
},
selectType: 'checkbox',
SelectInputComponent: defaultSelectInputComponent,
SelectAllInputComponent: defaultSelectInputComponent,
}
return wrapper
}
+79
View File
@@ -0,0 +1,79 @@
/* eslint-disable */
import React from 'react'
export default Component => {
const wrapper = class RTTreeTable extends React.Component {
constructor(props) {
super(props)
this.getWrappedInstance.bind(this)
this.TrComponent.bind(this)
this.getTrProps.bind(this)
}
// this is so we can expose the underlying ReactTable to get at the sortedData for selectAll
getWrappedInstance = () => {
if (!this.wrappedInstance) console.warn('RTTreeTable - No wrapped instance')
if (this.wrappedInstance.getWrappedInstance) return this.wrappedInstance.getWrappedInstance()
else return this.wrappedInstance
}
TrComponent = props => {
const { ri, ...rest } = props
if (ri && ri.groupedByPivot) {
const cell = { ...props.children[ri.level] }
cell.props.style.flex = 'unset'
cell.props.style.width = '100%'
cell.props.style.maxWidth = 'unset'
cell.props.style.paddingLeft = `${this.props.treeTableIndent * ri.level}px`
// cell.props.style.backgroundColor = '#DDD';
cell.props.style.borderBottom = '1px solid rgba(128,128,128,0.2)'
return (
<div className={`rt-tr ${rest.className}`} role="row" style={rest.style}>
{cell}
</div>
)
}
return <Component.defaultProps.TrComponent {...rest} />
}
getTrProps = (state, ri, ci, instance) => {
return { ri }
}
render() {
const { columns, treeTableIndent, ...rest } = this.props
const { TrComponent, getTrProps } = this
const extra = {
columns: columns.map(col => {
let column = col
if (rest.pivotBy && (rest.pivotBy.includes(col.accessor) || rest.pivotBy.includes(col.id))) {
column = {
id: col.id,
accessor: col.accessor,
width: `${treeTableIndent}px`,
show: false,
Header: '',
Expander: col.Expander,
PivotValue: col.PivotValue,
Pivot: col.Pivot,
}
}
return column
}),
TrComponent,
getTrProps,
}
return <Component {...rest} {...extra} ref={r => (this.wrappedInstance = r)} />
}
}
wrapper.displayName = 'RTTreeTable'
wrapper.defaultProps = {
treeTableIndent: 10,
}
return wrapper
}
+377 -359
View File
File diff suppressed because it is too large Load Diff
+25 -35
View File
@@ -2,6 +2,15 @@ $easeOutQuad = cubic-bezier(0.250, 0.460, 0.450, 0.940)
$easeOutBack = cubic-bezier(0.175, 0.885, 0.320, 1.275)
$expandSize = 7px
input-select-style()
border: 1px solid rgba(0,0,0,0.1)
background: white
padding: 5px 7px
font-size: inherit
border-radius: 3px
font-weight: normal
outline:none
.ReactTable
position:relative
display: flex
@@ -10,7 +19,7 @@ $expandSize = 7px
*
box-sizing: border-box
.rt-table
flex: 1
flex: auto 1
display: flex
flex-direction: column
align-items: stretch
@@ -21,7 +30,6 @@ $expandSize = 7px
.rt-thead
flex: 1 0 auto
display: flex
// overflow-y: scroll
flex-direction: column
-webkit-user-select: none;
-moz-user-select: none;
@@ -35,6 +43,10 @@ $expandSize = 7px
&.-filters
border-bottom: 1px solid alpha(black, 0.05)
input
select
input-select-style();
.rt-th
border-right: 1px solid alpha(black, 0.02)
@@ -61,6 +73,9 @@ $expandSize = 7px
&:last-child
border-right: 0
.rt-th:focus
outline: none
.rt-resizable-header
overflow: visible
&:last-child
@@ -111,6 +126,7 @@ $expandSize = 7px
border-right:0
.rt-expandable
cursor: pointer
text-overflow: clip
.rt-tr-group
flex: 1 0 auto
display: flex
@@ -169,6 +185,7 @@ $expandSize = 7px
z-index: 10
.rt-tfoot
flex: 1 0 auto
display: flex
flex-direction: column
box-shadow: 0 0px 15px 0px alpha(black, .15)
@@ -196,6 +213,10 @@ $expandSize = 7px
box-shadow: 0 0px 15px 0px alpha(black, .1)
border-top: 2px solid alpha(black, .1)
input
select
input-select-style()
.-btn
appearance:none
display:block
@@ -270,7 +291,7 @@ $expandSize = 7px
bottom:0
background: alpha(white, .8)
transition: all .3s ease
z-index: 2
z-index: -1
opacity: 0
pointer-events: none
@@ -288,42 +309,11 @@ $expandSize = 7px
&.-active
opacity: 1
z-index: 2
pointer-events: all
> div
transform: translateY(50%)
input
select
border: 1px solid rgba(0,0,0,0.1)
background: white
padding: 5px 7px
font-size: inherit
border-radius: 3px
font-weight: normal
outline:none
input:not([type="checkbox"]):not([type="radio"])
select
appearance: none
&::-ms-expand
display: none
.select-wrap
position:relative
display:inline-block
select
padding: 5px 15px 5px 7px
min-width:100px
&:after
content: ''
position: absolute
right: 8px
top: 50%
transform: translate(0, -50%)
border-color: #999 transparent transparent
border-style: solid
border-width: 5px 5px 2.5px
.rt-resizing
.rt-th
.rt-td
+114 -86
View File
@@ -1,100 +1,128 @@
export default Base => class extends Base {
componentWillMount () {
this.setStateWithData(this.getDataModel(this.getResolvedState()))
}
componentDidMount () {
this.fireFetchData()
}
componentWillReceiveProps (nextProps, nextState) {
const oldState = this.getResolvedState()
const newState = this.getResolvedState(nextProps, nextState)
// Do a deep compare of new and old `defaultOption` and
// if they are different reset `option = defaultOption`
const defaultableOptions = ['sorted', 'filtered', 'resized', 'expanded']
defaultableOptions.forEach(x => {
const defaultName = `default${x.charAt(0).toUpperCase() + x.slice(1)}`
if (JSON.stringify(oldState[defaultName]) !== JSON.stringify(newState[defaultName])) {
newState[x] = newState[defaultName]
}
})
// If they change these table options, we need to reset defaults
// or else we could get into a state where the user has changed the UI
// and then disabled the ability to change it back.
// e.g. If `filterable` has changed, set `filtered = defaultFiltered`
const resettableOptions = ['sortable', 'filterable', 'resizable']
resettableOptions.forEach(x => {
if (oldState[x] !== newState[x]) {
const baseName = x.replace('able', '')
const optionName = `${baseName}ed`
const defaultName = `default${optionName.charAt(0).toUpperCase() + optionName.slice(1)}`
newState[optionName] = newState[defaultName]
}
})
// Props that trigger a data update
if (
oldState.data !== newState.data ||
oldState.columns !== newState.columns ||
oldState.pivotBy !== newState.pivotBy ||
oldState.sorted !== newState.sorted ||
oldState.filtered !== newState.filtered
) {
this.setStateWithData(this.getDataModel(newState))
export default Base =>
class extends Base {
componentWillMount () {
this.setStateWithData(this.getDataModel(this.getResolvedState(), true))
}
}
setStateWithData (newState, cb) {
const oldState = this.getResolvedState()
const newResolvedState = this.getResolvedState({}, newState)
const {freezeWhenExpanded} = newResolvedState
componentDidMount () {
this.fireFetchData()
}
// Default to unfrozen state
newResolvedState.frozen = false
componentWillReceiveProps (nextProps, nextState) {
const oldState = this.getResolvedState()
const newState = this.getResolvedState(nextProps, nextState)
// If freezeWhenExpanded is set, check for frozen conditions
if (freezeWhenExpanded) {
// if any rows are expanded, freeze the existing data and sorting
const keys = Object.keys(newResolvedState.expanded)
for (var i = 0; i < keys.length; i++) {
if (newResolvedState.expanded[keys[i]]) {
newResolvedState.frozen = true
break
// Do a deep compare of new and old `defaultOption` and
// if they are different reset `option = defaultOption`
const defaultableOptions = ['sorted', 'filtered', 'resized', 'expanded']
defaultableOptions.forEach(x => {
const defaultName = `default${x.charAt(0).toUpperCase() + x.slice(1)}`
if (JSON.stringify(oldState[defaultName]) !== JSON.stringify(newState[defaultName])) {
newState[x] = newState[defaultName]
}
})
// If they change these table options, we need to reset defaults
// or else we could get into a state where the user has changed the UI
// and then disabled the ability to change it back.
// e.g. If `filterable` has changed, set `filtered = defaultFiltered`
const resettableOptions = ['sortable', 'filterable', 'resizable']
resettableOptions.forEach(x => {
if (oldState[x] !== newState[x]) {
const baseName = x.replace('able', '')
const optionName = `${baseName}ed`
const defaultName = `default${optionName.charAt(0).toUpperCase() + optionName.slice(1)}`
newState[optionName] = newState[defaultName]
}
})
// Props that trigger a data update
if (
oldState.data !== newState.data ||
oldState.columns !== newState.columns ||
oldState.pivotBy !== newState.pivotBy ||
oldState.sorted !== newState.sorted ||
oldState.filtered !== newState.filtered
) {
this.setStateWithData(this.getDataModel(newState, oldState.data !== newState.data))
}
}
setStateWithData (newState, cb) {
const oldState = this.getResolvedState()
const newResolvedState = this.getResolvedState({}, newState)
const { freezeWhenExpanded } = newResolvedState
// Default to unfrozen state
newResolvedState.frozen = false
// If freezeWhenExpanded is set, check for frozen conditions
if (freezeWhenExpanded) {
// if any rows are expanded, freeze the existing data and sorting
const keys = Object.keys(newResolvedState.expanded)
for (let i = 0; i < keys.length; i += 1) {
if (newResolvedState.expanded[keys[i]]) {
newResolvedState.frozen = true
break
}
}
}
}
// If the data isn't frozen and either the data or
// sorting model has changed, update the data
if (
(oldState.frozen && !newResolvedState.frozen) ||
oldState.sorted !== newResolvedState.sorted ||
oldState.filtered !== newResolvedState.filtered ||
oldState.showFilters !== newResolvedState.showFilters ||
(!newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData)
) {
// Handle collapseOnsortedChange & collapseOnDataChange
// If the data isn't frozen and either the data or
// sorting model has changed, update the data
if (
(oldState.sorted !== newResolvedState.sorted && this.props.collapseOnSortingChange) ||
(oldState.filtered !== newResolvedState.filtered) ||
(oldState.showFilters !== newResolvedState.showFilters) ||
(!newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData && this.props.collapseOnDataChange)
(oldState.frozen && !newResolvedState.frozen) ||
oldState.sorted !== newResolvedState.sorted ||
oldState.filtered !== newResolvedState.filtered ||
oldState.showFilters !== newResolvedState.showFilters ||
(!newResolvedState.frozen && oldState.resolvedData !== newResolvedState.resolvedData)
) {
newResolvedState.expanded = {}
// Handle collapseOnsortedChange & collapseOnDataChange
if (
(oldState.sorted !== newResolvedState.sorted && this.props.collapseOnSortingChange) ||
oldState.filtered !== newResolvedState.filtered ||
oldState.showFilters !== newResolvedState.showFilters ||
(oldState.sortedData &&
!newResolvedState.frozen &&
oldState.resolvedData !== newResolvedState.resolvedData &&
this.props.collapseOnDataChange)
) {
newResolvedState.expanded = {}
}
Object.assign(newResolvedState, this.getSortedData(newResolvedState))
}
Object.assign(newResolvedState, this.getSortedData(newResolvedState))
}
// Set page to 0 if filters change
if (oldState.filtered !== newResolvedState.filtered) {
newResolvedState.page = 0
}
// Calculate pageSize all the time
if (newResolvedState.sortedData) {
newResolvedState.pages = newResolvedState.manual ? newResolvedState.pages : Math.ceil(newResolvedState.sortedData.length / newResolvedState.pageSize)
newResolvedState.page = Math.max(newResolvedState.page >= newResolvedState.pages ? newResolvedState.pages - 1 : newResolvedState.page, 0)
}
// Calculate pageSize all the time
if (newResolvedState.sortedData) {
newResolvedState.pages = newResolvedState.manual
? newResolvedState.pages
: Math.ceil(newResolvedState.sortedData.length / newResolvedState.pageSize)
newResolvedState.page = newResolvedState.manual ? newResolvedState.page : Math.max(
newResolvedState.page >= newResolvedState.pages
? newResolvedState.pages - 1
: newResolvedState.page,
0
)
}
return this.setState(newResolvedState, cb)
return this.setState(newResolvedState, () => {
if (cb) {
cb()
}
if (
oldState.page !== newResolvedState.page ||
oldState.pageSize !== newResolvedState.pageSize ||
oldState.sorted !== newResolvedState.sorted ||
oldState.filtered !== newResolvedState.filtered
) {
this.fireFetchData()
}
})
}
}
}
+614 -559
View File
File diff suppressed because it is too large Load Diff
+103 -64
View File
@@ -1,31 +1,76 @@
import React, { Component } from 'react'
import classnames from 'classnames'
//
// import _ from './utils'
const defaultButton = (props) => (
<button type='button' {...props} className='-btn'>{props.children}</button>
const defaultButton = props => (
<button type="button" {...props} className="-btn">
{props.children}
</button>
)
export default class ReactTablePagination extends Component {
static defaultProps = {
PreviousComponent: defaultButton,
NextComponent: defaultButton,
renderPageJump: ({
onChange, value, onBlur, onKeyPress, inputType, pageJumpText,
}) => (
<div className="-pageJump">
<input
aria-label={pageJumpText}
type={inputType}
onChange={onChange}
value={value}
onBlur={onBlur}
onKeyPress={onKeyPress}
/>
</div>
),
renderCurrentPage: page => <span className="-currentPage">{page + 1}</span>,
renderTotalPagesCount: pages => <span className="-totalPages">{pages || 1}</span>,
renderPageSizeOptions: ({
pageSize,
pageSizeOptions,
rowsSelectorText,
onPageSizeChange,
rowsText,
}) => (
<span className="select-wrap -pageSizeOptions">
<select
aria-label={rowsSelectorText}
onChange={e => onPageSizeChange(Number(e.target.value))}
value={pageSize}
>
{pageSizeOptions.map((option, i) => (
// eslint-disable-next-line react/no-array-index-key
<option key={i} value={option}>
{`${option} ${rowsText}`}
</option>
))}
</select>
</span>
),
}
constructor (props) {
super()
super(props)
this.getSafePage = this.getSafePage.bind(this)
this.changePage = this.changePage.bind(this)
this.applyPage = this.applyPage.bind(this)
this.state = {
page: props.page
page: props.page,
}
}
componentWillReceiveProps (nextProps) {
this.setState({page: nextProps.page})
if (this.props.page !== nextProps.page) {
this.setState({ page: nextProps.page })
}
}
getSafePage (page) {
if (isNaN(page)) {
if (Number.isNaN(page)) {
page = this.props.page
}
return Math.min(Math.max(page, 0), this.props.pages - 1)
@@ -33,18 +78,42 @@ export default class ReactTablePagination extends Component {
changePage (page) {
page = this.getSafePage(page)
this.setState({page})
this.setState({ page })
if (this.props.page !== page) {
this.props.onPageChange(page)
}
}
applyPage (e) {
e && e.preventDefault()
if (e) {
e.preventDefault()
}
const page = this.state.page
this.changePage(page === '' ? this.props.page : page)
}
getPageJumpProperties () {
return {
onKeyPress: e => {
if (e.which === 13 || e.keyCode === 13) {
this.applyPage()
}
},
onBlur: this.applyPage,
value: this.state.page === '' ? '' : this.state.page + 1,
onChange: e => {
const val = e.target.value
const page = val - 1
if (val === '') {
return this.setState({ page: val })
}
this.setState({ page: this.getSafePage(page) })
},
inputType: this.state.page === '' ? 'text' : 'number',
pageJumpText: this.props.pageJumpText,
}
}
render () {
const {
// Computed
@@ -59,18 +128,19 @@ export default class ReactTablePagination extends Component {
canNext,
onPageSizeChange,
className,
PreviousComponent = defaultButton,
NextComponent = defaultButton
PreviousComponent,
NextComponent,
renderPageJump,
renderCurrentPage,
renderTotalPagesCount,
renderPageSizeOptions,
} = this.props
return (
<div
className={classnames(className, '-pagination')}
style={this.props.paginationStyle}
>
<div className='-previous'>
<div className={classnames(className, '-pagination')} style={this.props.style}>
<div className="-previous">
<PreviousComponent
onClick={(e) => {
onClick={() => {
if (!canPrevious) return
this.changePage(page - 1)
}}
@@ -79,55 +149,24 @@ export default class ReactTablePagination extends Component {
{this.props.previousText}
</PreviousComponent>
</div>
<div className='-center'>
<span className='-pageInfo'>
{this.props.pageText} {showPageJump ? (
<div className='-pageJump'>
<input
type={this.state.page === '' ? 'text' : 'number'}
onChange={e => {
const val = e.target.value
const page = val - 1
if (val === '') {
return this.setState({page: val})
}
this.setState({page: this.getSafePage(page)})
}}
value={this.state.page === '' ? '' : this.state.page + 1}
onBlur={this.applyPage}
onKeyPress={e => {
if (e.which === 13 || e.keyCode === 13) {
this.applyPage()
}
}}
/>
</div>
) : (
<span className='-currentPage'>{page + 1}</span>
)} {this.props.ofText} <span className='-totalPages'>{pages || 1}</span>
<div className="-center">
<span className="-pageInfo">
{this.props.pageText}{' '}
{showPageJump ? renderPageJump(this.getPageJumpProperties()) : renderCurrentPage(page)}{' '}
{this.props.ofText} {renderTotalPagesCount(pages)}
</span>
{showPageSizeOptions && (
<span className='select-wrap -pageSizeOptions'>
<select
onChange={(e) => onPageSizeChange(Number(e.target.value))}
value={pageSize}
>
{pageSizeOptions.map((option, i) => {
return (
<option
key={i}
value={option}>
{option} {this.props.rowsText}
</option>
)
})}
</select>
</span>
)}
{showPageSizeOptions &&
renderPageSizeOptions({
pageSize,
rowsSelectorText: this.props.rowsSelectorText,
pageSizeOptions,
onPageSizeChange,
rowsText: this.props.rowsText,
})}
</div>
<div className='-next'>
<div className="-next">
<NextComponent
onClick={(e) => {
onClick={() => {
if (!canNext) return
this.changePage(page + 1)
}}
+169
View File
@@ -0,0 +1,169 @@
import PropTypes from 'prop-types'
export default {
// General
data: PropTypes.any,
loading: PropTypes.bool,
showPagination: PropTypes.bool,
showPaginationTop: PropTypes.bool,
showPaginationBottom: PropTypes.bool,
showPageSizeOptions: PropTypes.bool,
pageSizeOptions: PropTypes.array,
defaultPageSize: PropTypes.number,
showPageJump: PropTypes.bool,
collapseOnSortingChange: PropTypes.bool,
collapseOnPageChange: PropTypes.bool,
collapseOnDataChange: PropTypes.bool,
freezeWhenExpanded: PropTypes.bool,
sortable: PropTypes.bool,
resizable: PropTypes.bool,
filterable: PropTypes.bool,
defaultSortDesc: PropTypes.bool,
defaultSorted: PropTypes.array,
defaultFiltered: PropTypes.array,
defaultResized: PropTypes.array,
defaultExpanded: PropTypes.object,
defaultFilterMethod: PropTypes.func,
defaultSortMethod: PropTypes.func,
// Controlled State Callbacks
onPageChange: PropTypes.func,
onPageSizeChange: PropTypes.func,
onSortedChange: PropTypes.func,
onFilteredChange: PropTypes.func,
onResizedChange: PropTypes.func,
onExpandedChange: PropTypes.func,
// Pivoting
pivotBy: PropTypes.array,
// Key Constants
pivotValKey: PropTypes.string,
pivotIDKey: PropTypes.string,
subRowsKey: PropTypes.string,
aggregatedKey: PropTypes.string,
nestingLevelKey: PropTypes.string,
originalKey: PropTypes.string,
indexKey: PropTypes.string,
groupedByPivotKey: PropTypes.string,
// Server-side Callbacks
onFetchData: PropTypes.func,
// Classes
className: PropTypes.string,
style: PropTypes.object,
// Component decorators
getProps: PropTypes.func,
getTableProps: PropTypes.func,
getTheadGroupProps: PropTypes.func,
getTheadGroupTrProps: PropTypes.func,
getTheadGroupThProps: PropTypes.func,
getTheadProps: PropTypes.func,
getTheadTrProps: PropTypes.func,
getTheadThProps: PropTypes.func,
getTheadFilterProps: PropTypes.func,
getTheadFilterTrProps: PropTypes.func,
getTheadFilterThProps: PropTypes.func,
getTbodyProps: PropTypes.func,
getTrGroupProps: PropTypes.func,
getTrProps: PropTypes.func,
getTdProps: PropTypes.func,
getTfootProps: PropTypes.func,
getTfootTrProps: PropTypes.func,
getTfootTdProps: PropTypes.func,
getPaginationProps: PropTypes.func,
getLoadingProps: PropTypes.func,
getNoDataProps: PropTypes.func,
getResizerProps: PropTypes.func,
// Global Column Defaults
columns: PropTypes.arrayOf(
PropTypes.shape({
// Renderers
Cell: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
Header: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
Footer: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
Aggregated: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
Pivot: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
PivotValue: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
Expander: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.func]),
Filter: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
// All Columns
sortable: PropTypes.bool, // use table default
resizable: PropTypes.bool, // use table default
filterable: PropTypes.bool, // use table default
show: PropTypes.bool,
minWidth: PropTypes.number,
minResizeWidth: PropTypes.number,
// Cells only
className: PropTypes.string,
style: PropTypes.object,
getProps: PropTypes.func,
// Pivot only
aggregate: PropTypes.func,
// Headers only
headerClassName: PropTypes.string,
headerStyle: PropTypes.object,
getHeaderProps: PropTypes.func,
// Footers only
footerClassName: PropTypes.string,
footerStyle: PropTypes.object,
getFooterProps: PropTypes.func,
filterMethod: PropTypes.func,
filterAll: PropTypes.bool,
sortMethod: PropTypes.func,
})
),
// Global Expander Column Defaults
expanderDefaults: PropTypes.shape({
sortable: PropTypes.bool,
resizable: PropTypes.bool,
filterable: PropTypes.bool,
width: PropTypes.number,
}),
pivotDefaults: PropTypes.object,
// Text
previousText: PropTypes.node,
nextText: PropTypes.node,
loadingText: PropTypes.node,
noDataText: PropTypes.node,
pageText: PropTypes.node,
ofText: PropTypes.node,
rowsText: PropTypes.node,
pageJumpText: PropTypes.node,
rowsSelectorText: PropTypes.node,
// Components
TableComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
TheadComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
TbodyComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
TrGroupComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
TrComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
ThComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
TdComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
TfootComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
FilterComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
ExpanderComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
PivotValueComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
AggregatedComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
// this is a computed default generated using
PivotComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
// the ExpanderComponent and PivotValueComponent at run-time in methods.js
PaginationComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
PreviousComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
NextComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
LoadingComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
NoDataComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
ResizerComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
PadRowComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
}
+75 -42
View File
@@ -10,6 +10,8 @@ export default {
range,
remove,
clone,
leaves,
iterTree,
getFirstDefined,
sum,
makeTemplateComponent,
@@ -18,7 +20,8 @@ export default {
splitProps,
compactObject,
isSortingDesc,
normalizeComponent
normalizeComponent,
asPx,
}
function get (obj, path, def) {
@@ -29,7 +32,9 @@ function get (obj, path, def) {
let val
try {
val = pathObj.reduce((current, pathPart) => current[pathPart], obj)
} catch (e) {}
} catch (e) {
// continue regardless of error
}
return typeof val !== 'undefined' ? val : def
}
@@ -58,7 +63,7 @@ function last (arr) {
function range (n) {
const arr = []
for (let i = 0; i < n; i++) {
for (let i = 0; i < n; i += 1) {
arr.push(n)
}
return arr
@@ -66,7 +71,7 @@ function range (n) {
function orderBy (arr, funcs, dirs, indexKey) {
return arr.sort((rowA, rowB) => {
for (let i = 0; i < funcs.length; i++) {
for (let i = 0; i < funcs.length; i += 1) {
const comp = funcs[i]
const desc = dirs[i] === false || dirs[i] === 'desc'
const sortInt = comp(rowA, rowB)
@@ -75,15 +80,13 @@ function orderBy (arr, funcs, dirs, indexKey) {
}
}
// Use the row index for tie breakers
return dirs[0]
? rowA[indexKey] - rowB[indexKey]
: rowB[indexKey] - rowA[indexKey]
return dirs[0] ? rowA[indexKey] - rowB[indexKey] : rowB[indexKey] - rowA[indexKey]
})
}
function remove (a, b) {
return a.filter(function (o, i) {
var r = b(o)
return a.filter((o, i) => {
const r = b(o)
if (r) {
a.splice(i, 1)
return true
@@ -94,19 +97,39 @@ function remove (a, b) {
function clone (a) {
try {
return JSON.parse(JSON.stringify(a, (key, value) => {
if (typeof value === 'function') {
return value.toString()
}
return value
}))
return JSON.parse(
JSON.stringify(a, (key, value) => {
if (typeof value === 'function') {
return value.toString()
}
return value
})
)
} catch (e) {
return a
}
}
function leaves (root, childProperty) {
if (Object.prototype.hasOwnProperty.call(root, childProperty)) {
const children = root[childProperty].map(child => leaves(child, childProperty))
return [].concat(...children)
}
return [root]
}
function iterTree (root, childProperty) {
if (Object.prototype.hasOwnProperty.call(root, childProperty)) {
const children = root[childProperty].map(child => leaves(child, childProperty))
return [].concat(root, ...children)
}
return [root]
}
function getFirstDefined (...args) {
for (var i = 0; i < args.length; i++) {
for (let i = 0; i < args.length; i += 1) {
if (typeof args[i] !== 'undefined') {
return args[i]
}
@@ -114,20 +137,20 @@ function getFirstDefined (...args) {
}
function sum (arr) {
return arr.reduce((a, b) => {
return a + b
}, 0)
return arr.reduce((a, b) => a + b, 0)
}
function makeTemplateComponent (compClass) {
return ({children, className, ...rest}) => (
<div
className={classnames(compClass, className)}
{...rest}
>
function makeTemplateComponent (compClass, displayName) {
if (!displayName) {
throw new Error('No displayName found for template component:', compClass)
}
const cmp = ({ children, className, ...rest }) => (
<div className={classnames(compClass, className)} {...rest}>
{children}
</div>
)
cmp.displayName = displayName
return cmp
}
function groupBy (xs, key) {
@@ -139,6 +162,11 @@ function groupBy (xs, key) {
}, {})
}
function asPx (value) {
value = Number(value)
return Number.isNaN(value) ? null : `${value}px`
}
function isArray (a) {
return Array.isArray(a)
}
@@ -149,37 +177,44 @@ function isArray (a) {
function makePathArray (obj) {
return flattenDeep(obj)
.join('.')
.replace('[', '.')
.replace(']', '')
.split('.')
.join('.')
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
}
function flattenDeep (arr, newArr = []) {
if (!isArray(arr)) {
newArr.push(arr)
} else {
for (var i = 0; i < arr.length; i++) {
for (let i = 0; i < arr.length; i += 1) {
flattenDeep(arr[i], newArr)
}
}
return newArr
}
function splitProps ({className, style, ...rest}) {
function splitProps ({ className, style, ...rest }) {
return {
className,
style,
rest
rest: rest || {},
}
}
function compactObject (obj) {
const newObj = {}
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key] !== undefined && typeof obj[key] !== 'undefined') {
newObj[key] = obj[key]
}
if (obj) {
Object.keys(obj).map(key => {
if (
Object.prototype.hasOwnProperty.call(obj, key) &&
obj[key] !== undefined &&
typeof obj[key] !== 'undefined'
) {
newObj[key] = obj[key]
}
return true
})
}
return newObj
}
@@ -190,10 +225,8 @@ function isSortingDesc (d) {
function normalizeComponent (Comp, params = {}, fallback = Comp) {
return typeof Comp === 'function' ? (
Object.getPrototypeOf(Comp).isReactComponent ? (
<Comp
{...params}
/>
) : Comp(params)
) : fallback
<Comp {...params} />
) : (
fallback
)
}
-20
View File
@@ -1,20 +0,0 @@
const webpack = require('webpack')
module.exports = {
entry: './lib/index.js',
output: {
filename: './react-table.js',
libraryTarget: 'umd',
library: 'ReactTable'
},
externals: {
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
}
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
}
+1709 -1364
View File
File diff suppressed because it is too large Load Diff