Compare commits

...
26 changed files with 11202 additions and 121 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
module.exports = {
hooks: {
'pre-commit': 'lint-staged',
'pre-commit': 'lint-staged && yarn test:ci',
'commit-msg': 'commitlint -E HUSKY_GIT_PARAMS',
},
}
+208 -30
View File
@@ -167,6 +167,7 @@ import {
- [Sorting - Client Side](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting-client-side)
- [Filtering - Client Side](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering-client-side)
- [Grouping - Client Side](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping-client-side)
- [Pagination - Client Side](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination-client-side)
# Concepts
@@ -330,7 +331,7 @@ The following options are supported on any column object you can pass to `column
- Must return valid JSX
- This function (or component) is primarily used for formatting the column value, eg. If your column accessor returns a date object, you can use a `Cell` function to format that date to a readable format.
### `Instance` Properties
### Instance Properties
The following properties are available on the table instance returned from `useTable`
@@ -368,7 +369,7 @@ The following additional properties are available on every `headerGroup` object
- You can use the `getHeaderGroupProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
### `Column` Properties
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
@@ -386,7 +387,7 @@ The following properties are available on every `Column` object returned by the
- You can use the `getHeaderProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
### `Row` Properties
### Row Properties
The following additional properties are available on every `row` object returned by the table instance.
@@ -401,7 +402,7 @@ The following additional properties are available on every `row` object returned
- You can use the `getRowProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
### `Cell` Properties
### Cell Properties
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
@@ -539,7 +540,7 @@ The following options are supported via the main options object passed to `useTa
- Allows overriding or adding additional sort types for columns to use. If a column's sort type isn't found on this object, it will default to using the [built-in sort types](TODO).
- For mor information on sort types, see [Sorting](TODO)
### `Column` Options
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
@@ -564,7 +565,7 @@ The following options are supported on any `Column` object passed to the `column
- If a `function` is passed, it will be used.
- For mor information on sort types, see [Sorting](TODO)
### `Instance` Properties
### Instance Properties
The following values are provided to the table `instance`:
@@ -575,7 +576,7 @@ The following values are provided to the table `instance`:
- `toggleSortBy: Function(ColumnID: String, descending: Bool, isMulti: Bool) => void`
- This function can be used to programmatically toggle the sorting for any specific column
### `Column` Properties
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
@@ -686,7 +687,7 @@ The following options are supported via the main options object passed to `useTa
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the [built-in filter types](TODO).
- For mor information on filter types, see [Filtering](TODO)
### `Column` Options
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
@@ -707,7 +708,7 @@ The following options are supported on any `Column` object passed to the `column
- For mor information on filter types, see [Filtering](TODO)
- If a **function** is passed, it must be **memoized**
### `Instance` Properties
### Instance Properties
The following values are provided to the table `instance`:
@@ -721,7 +722,7 @@ The following values are provided to the table `instance`:
- `setAllFilters: Function(filtersObject) => void`
- An instance-level function used to update the values for **all** filters on the table, all at once.
### `Column` Properties
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
@@ -798,10 +799,6 @@ The following options are supported via the main options object passed to `useTa
- `state[0].groupBy: Array<String>`
- Must be **memoized**
- An array of groupBy ID strings, controlling which columns are used to calculate row grouping and aggregation. This information is stored in state since the table is allowed to manipulate the groupBy through user interaction.
- `groupByFn: Function`
- Must be **memoized**
- Defaults to [`defaultGroupByFn`](TODO)
- This function is responsible for grouping rows based on the `state.groupBy` keys provided. It's very rare you would need to customize this function.
- `manualGroupBy: Bool`
- Enables groupBy detection and functionality, but does not automatically perform row grouping.
- Turn this on if you wish to implement your own row grouping outside of the table (eg. server-side or manual row grouping/nesting)
@@ -810,8 +807,12 @@ The following options are supported via the main options object passed to `useTa
- `aggregations: Object<aggregationKey: aggregationFn>`
- Must be **memoized**
- Allows overriding or adding additional aggregation functions for use when grouping/aggregating row values. If an aggregation key isn't found on this object, it will default to using the [built-in aggregation functions](TODO)
- `groupByFn: Function`
- Must be **memoized**
- Defaults to [`defaultGroupByFn`](TODO)
- This function is responsible for grouping rows based on the `state.groupBy` keys provided. It's very rare you would need to customize this function.
### `Column` Options
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
@@ -825,7 +826,7 @@ The following options are supported on any `Column` object passed to the `column
- Defaults to `true`
- If `true`, this column is able to be grouped.
### `Instance` Properties
### Instance Properties
The following values are provided to the table `instance`:
@@ -836,7 +837,7 @@ The following values are provided to the table `instance`:
- `toggleGroupBy: Function(columnID: String, ?set: Bool) => void`
- This function can be used to programmatically set or toggle the groupBy state for a specific column.
### `Column` Properties
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
@@ -855,24 +856,201 @@ The following properties are available on every `Column` object returned by the
- You can use the `getGroupByToggleProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props may override built-in sortBy props, so be careful!**
### Row Properties
The following properties are available on every `Row` object returned by the table instance.
- `groupByID: String`
- The column ID for which this row is being grouped.
- Will be `undefined` if the row is an original row from `data` and not a materialized one from the grouping.
- `groupByVal: any`
- If the row is a materialized group row, this will be the grouping value that was used to create it.
- `values: Object`
- Similar to a regular row, a materialized grouping row also has a `values` object
- This object contains the **aggregated** values for this row's sub rows
- `subRows: Array<Row>`
- If the row is a materialized group row, this property is the array of materialized subRows that were grouped inside of this row.
- `depth: Int`
- If the row is a materialized group row, this is the grouping depth at which this row was created.
- `path: Array<String|Int>`
- Similar to normal `Row` objects, materialized grouping rows also have a path array. The keys inside it though are not integers like nested normal rows though. Since they are not rows that can be traced back to an original data row, they are given a unique path based on their `groupByVal`
- If a row is a grouping row, it will have a path like `['Single']` or `['Complicated', 'Anderson']`, where `Single`, `Complicated`, and `Anderson` would all be derived from their row's `groupByVal`.
### Cell Properties
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
- `grouped: Bool`
- If `true`, this cell is a grouped cell, meaning it contains a grouping value and should usually display and expander.
- `repeatedValue: Bool`
- If `true`, this cell is a repeated value cell, meaning it contains a value that is already being displayed elsewhere (usually by a parent row's cell).
- Most of the time, this cell is not required to be displayed and can safely be hidden during rendering
- `aggregated: Bool`
- If `true`, this cell's value has been aggregated and should probably be rendered with the `Aggregated` cell renderer.
### Example
```js
const state = useTableState({ groupBy: ['firstName'] })
function Table({ columns, data }) {
const {
getTableProps,
headerGroups,
rows,
prepareRow,
state: [{ groupBy, expanded }],
} = useTable(
{
columns,
data,
},
useGroupBy,
useExpanded // useGroupBy would be pretty useless without useExpanded ;)
)
const aggregations = React.useMemo(() => ({
customSum: (values, rows) => values.reduce((sum, next) => sum + next, 0),
}))
// We don't want to render all 2000 rows for this example, so cap
// it at 20 for this use case
const firstPageRows = rows.slice()
const { rows } = useTable(
{
state, // state[0].groupBy === ['firstName']
manualGroupBy: false,
disableGrouping: false,
aggregations,
},
useGroupBy
)
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.grouped ? '🛑' : '👊'}
</span>
) : null}
{column.render('Header')}
</th>
))}
</tr>
))}
</thead>
<tbody>
{firstPageRows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>
{cell.grouped ? (
// If it's a grouped cell, add an expander and row count
<>
<span
style={{
cursor: 'pointer',
}}
onClick={() => row.toggleExpanded()}
>
{row.isExpanded ? '👇' : '👉'}
</span>
{cell.render('Cell')} ({row.subRows.length})
</>
) : cell.aggregated ? (
// If the cell is aggregated, use the Aggregated
// renderer for cell
cell.render('Aggregated')
) : cell.repeatedValue ? null : ( // For cells with repeated values, render null
// Otherwise, just render the regular cell
cell.render('Cell')
)}
</td>
)
})}
</tr>
)
)}
</tbody>
</table>
)
}
// This is a custom aggregator that
// takes in an array of values and
// returns the rounded median
function roundedMedian(values) {
let min = values[0] || ''
let max = values[0] || ''
values.forEach(value => {
min = Math.min(min, value)
max = Math.max(max, value)
})
return Math.round((min + max) / 2)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
// Use a two-stage aggregator here to first
// count the total rows being aggregated,
// then sum any of those counts if they are
// aggregated further
aggregate: ['sum', 'count'],
Aggregated: ({ value }) => `${value} Names`,
},
{
Header: 'Last Name',
accessor: 'lastName',
// Use another two-stage aggregator here to
// first count the UNIQUE values from the rows
// being aggregated, then sum those counts if
// they are aggregated further
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ value }) => `${value} Unique Names`,
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
// Aggregate the average age of visitors
aggregate: 'average',
Aggregated: ({ value }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
// Aggregate the sum of all visits
aggregate: 'sum',
Aggregated: ({ value }) => `${value} (total)`,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
// Use our custom roundedMedian aggregator
aggregate: roundedMedian,
Aggregated: ({ value }) => `${value} (med)`,
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(10000), [])
return <Table columns={columns} data={data} />
}
```
## `useExpanded`
+11 -11
View File
@@ -123,9 +123,9 @@ function SliderColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
function NumberRangeColumnFilter({ filterValue = [], setFilter }) {
return (
<div
css={`
display: flex;
`}
style={{
display: 'flex',
}}
>
<input
value={filterValue[0] || ''}
@@ -135,10 +135,10 @@ function NumberRangeColumnFilter({ filterValue = [], setFilter }) {
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
}}
placeholder="Min"
css={`
width: 70px;
margin-right: 0.5rem;
`}
style={{
width: '70px',
marginRight: '0.5rem',
}}
/>
to
<input
@@ -149,10 +149,10 @@ function NumberRangeColumnFilter({ filterValue = [], setFilter }) {
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
}}
placeholder="Max"
css={`
width: 70px;
margin-left: 0.5rem;
`}
style={{
width: '70px',
marginLeft: '0.5rem',
}}
/>
</div>
)
+30 -29
View File
@@ -46,7 +46,7 @@ function Table({ columns, data }) {
data,
},
useGroupBy,
useExpanded
useExpanded // useGroupBy would be pretty useless without useExpanded ;)
)
// We don't want to render all 2000 rows for this example, so cap
@@ -64,19 +64,14 @@ function Table({ columns, data }) {
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
// Add the sorting props to control sorting. For this example
// we can add them into the header props
<th {...column.getHeaderProps()}>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.grouped ? '🛑' : '👊'}
</span>
) : null}
{column.render('Header')}
{/* Add a sort direction indicator */}
<span>
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
</th>
))}
</tr>
@@ -90,6 +85,9 @@ function Table({ columns, data }) {
{row.cells.map(cell => {
return (
<td
// For educational purposes, let's color the
// cell depending on what type it is given
// from the useGroupBy hook
{...cell.getCellProps()}
style={{
background: cell.grouped
@@ -102,7 +100,7 @@ function Table({ columns, data }) {
}}
>
{cell.grouped ? (
// Add an expander and row count to the grouped cell
// If it's a grouped cell, add an expander and row count
<>
<span
style={{
@@ -115,8 +113,8 @@ function Table({ columns, data }) {
{cell.render('Cell')} ({row.subRows.length})
</>
) : cell.aggregated ? (
// Use the Aggregated renderer for cells that have
// aggregated values
// If the cell is aggregated, use the Aggregated
// renderer for cell
cell.render('Aggregated')
) : cell.repeatedValue ? null : ( // For cells with repeated values, render null
// Otherwise, just render the regular cell
@@ -139,34 +137,34 @@ function Table({ columns, data }) {
function Legend() {
return (
<div
css={`
padding: 0.5rem 0;
`}
style={{
padding: '0.5rem 0',
}}
>
<span
css={`
display: inline-block;
background: #0aff0082;
padding: 0.5rem;
`}
style={{
display: 'inline-block',
background: '#0aff0082',
padding: '0.5rem',
}}
>
Grouped
</span>{' '}
<span
css={`
display: inline-block;
background: #ffa50078;
padding: 0.5rem;
`}
style={{
display: 'inline-block',
background: '#ffa50078',
padding: '0.5rem',
}}
>
Aggregated
</span>{' '}
<span
css={`
display: inline-block;
background: #ff000042;
padding: 0.5rem;
`}
style={{
display: 'inline-block',
background: '#ff000042',
padding: '0.5rem',
}}
>
Repeated Value
</span>
@@ -174,6 +172,9 @@ function Legend() {
)
}
// This is a custom aggregator that
// takes in an array of values and
// returns the rounded median
function roundedMedian(values) {
let min = values[0] || ''
let max = values[0] || ''
@@ -248,7 +249,7 @@ function App() {
[]
)
const data = React.useMemo(() => makeData(100), [])
const data = React.useMemo(() => makeData(10000), [])
return (
<Styles>
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
- `yarn` and `yarn start` to run and edit the example
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
@@ -0,0 +1,3 @@
{
"infiniteLoopProtection": false
}
+212
View File
@@ -0,0 +1,212 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, usePagination } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
.pagination {
padding: 0.5rem;
}
`
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we'll use page,
// which has only the rows for the active page
// The rest of these things are super handy, too ;)
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
state: [{ pageIndex, pageSize }],
} = useTable(
{
columns,
data,
},
usePagination
)
// Render the UI for your table
return (
<>
<pre>
<code>
{JSON.stringify(
{
pageIndex,
pageSize,
pageCount,
canNextPage,
canPreviousPage,
},
null,
2
)}
</code>
</pre>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody>
{page.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)
)}
</tbody>
</table>
{/*
Pagination can be built however you'd like.
This is just a very basic UI implementation:
*/}
<div className="pagination">
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
{'<<'}
</button>{' '}
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
{'<'}
</button>{' '}
<button onClick={() => nextPage()} disabled={!canNextPage}>
{'>'}
</button>{' '}
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
{'>>'}
</button>{' '}
<span>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{' '}
</span>
<span>
| Go to page:{' '}
<input
type="number"
defaultValue={pageIndex + 1}
onChange={e => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
gotoPage(page)
}}
style={{ width: '100px' }}
/>
</span>{' '}
<select
value={pageSize}
onChange={e => {
setPageSize(Number(e.target.value))
}}
>
{[10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(100000), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
@@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(<App />, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
@@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config)
}
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
if (installingWorker == null) {
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
)
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration)
}
}
}
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
)
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister()
})
}
}
File diff suppressed because it is too large Load Diff
+6 -8
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-alpha.13",
"version": "7.0.0-alpha.15",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
@@ -30,13 +30,11 @@
"format": "prettier ./**{md,js,jsx,tsx} --write"
},
"files": [
"src/",
"es/",
"lib/",
"react-table.js",
"react-table.min.js",
"react-table.css",
"media/*.png"
"CHANGELOG.md",
"dist",
"LICENCE",
"package.json",
"README.md"
],
"peerDependencies": {
"prop-types": "^15.5.0",
@@ -0,0 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a sortable table 1`] = `
"Snapshot Diff:
Compared values have no visual difference."
`;
exports[`renders a sortable table 2`] = `
"Snapshot Diff:
Compared values have no visual difference."
`;
+157
View File
@@ -0,0 +1,157 @@
import '@testing-library/react/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import { useTable } from '../../hooks/useTable'
import { useFilters } from '../useFilters'
const data = [
{
firstName: 'tanner',
lastName: 'linsley',
age: 29,
visits: 100,
status: 'In Relationship',
progress: 50,
},
{
firstName: 'derek',
lastName: 'perkins',
age: 40,
visits: 40,
status: 'Single',
progress: 80,
},
{
firstName: 'joe',
lastName: 'bergevin',
age: 45,
visits: 20,
status: 'Complicated',
progress: 10,
},
{
firstName: 'jaylen',
lastName: 'linsley',
age: 26,
visits: 99,
status: 'In Relationship',
progress: 70,
},
]
const defaultColumn = {
Cell: ({ value, column: { id } }) => `${id}: ${value}`,
Filter: ({ filterValue, setFilter }) => (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}}
placeholder="Search..."
/>
),
}
function Table({ columns, data }) {
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
{
columns,
data,
defaultColumn,
},
useFilters
)
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.render('Header')}
{column.render('Filter')}
</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
))}
</tr>
)
)}
</tbody>
</table>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
return <Table columns={columns} data={data} />
}
test('renders a sortable table', () => {
const { getByText, asFragment } = render(<App />)
const beforeSort = asFragment()
fireEvent.click(getByText('First Name'))
const afterSort1 = asFragment()
fireEvent.click(getByText('First Name'))
const afterSort2 = asFragment()
expect(beforeSort).toMatchDiffSnapshot(afterSort1)
expect(afterSort1).toMatchDiffSnapshot(afterSort2)
})
+51 -42
View File
@@ -15,14 +15,18 @@ const propTypes = {
manualPagination: PropTypes.bool,
}
// SSR has issues with useLayoutEffect still, so pony-fill with useEffect during SSR
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
let useLayoutEffect =
typeof window !== 'undefined' && process.env.NODE_ENV === 'production'
? React.useLayoutEffect
: React.useEffect
export const usePagination = props => {
PropTypes.checkPropTypes(propTypes, props, 'property', 'usePagination')
export const usePagination = hooks => {
hooks.useMain.push(useMain)
}
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'usePagination')
const {
rows,
@@ -40,53 +44,58 @@ export const usePagination = props => {
},
setState,
],
} = props
const pageOptions = React.useMemo(
() => [...new Array(userPageCount)].map((d, i) => i),
[userPageCount]
)
} = instance
const rowDep = disablePageResetOnDataChange ? null : rows
useLayoutEffect(() => {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
}, [setState, rowDep, filters, groupBy, sortBy])
useLayoutEffect(
() => {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
},
[setState, rowDep, filters, groupBy, sortBy]
)
const { pages, pageCount } = React.useMemo(() => {
if (manualPagination) {
return {
pages: [rows],
pageCount: userPageCount,
const { pages, pageCount } = React.useMemo(
() => {
if (manualPagination) {
return {
pages: [rows],
pageCount: userPageCount,
}
}
}
if (debug) console.info('getPages')
if (debug) console.info('getPages')
// Create a new pages with the first page ready to go.
const pages = rows.length ? [] : [[]]
// Create a new pages with the first page ready to go.
const pages = rows.length ? [] : [[]]
// Start the pageIndex and currentPage cursors
let cursor = 0
while (cursor < rows.length) {
const end = cursor + pageSize
pages.push(rows.slice(cursor, end))
cursor = end
}
// Start the pageIndex and currentPage cursors
let cursor = 0
while (cursor < rows.length) {
const end = cursor + pageSize
pages.push(rows.slice(cursor, end))
cursor = end
}
const pageCount = pages.length
const pageCount = pages.length
return {
pages,
pageCount,
pageOptions,
}
}, [manualPagination, debug, rows, pageOptions, userPageCount, pageSize])
return {
pages,
pageCount,
}
},
[manualPagination, debug, rows, userPageCount, pageSize]
)
const pageOptions = React.useMemo(
() => [...new Array(pageCount)].map((d, i) => i),
[pageCount]
)
const page = manualPagination ? rows : pages[pageIndex] || []
const canPreviousPage = pageIndex > 0
@@ -126,7 +135,7 @@ export const usePagination = props => {
}
return {
...props,
...instance,
pages,
pageOptions,
pageCount,