Compare commits

...
Author SHA1 Message Date
tannerlinsley 727f4157c1 v7.0.0-beta.5 2019-10-01 20:49:07 -06:00
tannerlinsley 3f9ba8daba chore: user terser 2019-10-01 20:48:12 -06:00
tannerlinsley 3de1bbc3a7 v7.0.0-beta.4 2019-10-01 20:35:25 -06:00
tannerlinsley 7d84f86612 fix: cleanup 2019-10-01 20:34:37 -06:00
tannerlinsley 40477c1c83 fix: do not error on unkonwn user actions, side-effect-free 2019-10-01 20:33:55 -06:00
tannerlinsley 906988c35a Merge branch 'master' of https://github.com/react-tools/react-table 2019-10-01 14:26:11 -06:00
tannerlinsley 07d879f5bb docs(docs - example): updated example docs 2019-10-01 14:25:36 -06:00
Tanner LinsleyandGitHub e18f371623 Update README.md 2019-10-01 14:08:01 -06:00
tannerlinsley 76a55b5103 v7.0.0-beta.3 2019-10-01 14:04:05 -06:00
tannerlinsley 247687ee08 feat: ingested width logic, useAbsoluteLayout useBlockLayout
Width options (`width`, `minWidth`, `maxWidth`) options are now a part of the core column object.
useBlockLayout and useAbsoluteLayout hooks now use this new internalized information to implement
their layouts. Those examples have been updated. A virtualized-rows example has also been added to
show off how the useBlockLayout hook can be used to virtualize rows with react-window.
2019-10-01 14:03:11 -06:00
Julian BöhnkeandTanner Linsley f70d38e061 add material-ui table component example (#1557)
* add material-ui table component example

* remove unused styled-components package

* update to react-table@nex

* update sandbox link

* update docs

* Update examples.md
2019-09-30 12:48:10 -06:00
gargrohandTanner Linsley b6fdb99f06 useAbsoluteLayout: Enable react-table to build with divs (#1522)
* useAbsoluteLayout: To build tables with divs

* Adding `placeholderOf` attribute to column

* Adding `useAbsoluteLayout` in index.js

* Adding `useAbsoluteLayout` example

* Adding `useAbsoluteLayout` in api docs

* Adding test for `useAbsoluteLayout` hook
2019-09-30 07:40:35 -06:00
tannerlinsley 488da2ecc5 v7.0.0-beta.2 2019-09-30 07:32:56 -06:00
tannerlinsley 5f0e7cab8b fix: fix colspan prop to use column visibility
Fixes #1555
2019-09-30 07:31:43 -06:00
Nick OomsandTanner Linsley e2e67ed181 Added "in" to make the sentence more readable (#1554) 2019-09-28 06:44:01 -06:00
goldenLunchboxandTanner Linsley c8857a2871 Update api.md (#1551)
The state variable seemed to be missing in the useTable part (row 481) and I felt the need to comment on an additional import being needed.
2019-09-27 05:43:13 -06:00
Tanner LinsleyandGitHub 98583d35f3 Update README.md 2019-09-26 13:28:31 -06:00
tannerlinsley 0a1bf55a2c Merge branch 'master' of https://github.com/react-tools/react-table 2019-09-26 13:23:03 -06:00
tannerlinsley 54b4f8a5d1 v7.0.0-beta.1 2019-09-26 13:22:14 -06:00
tannerlinsley f552c94972 fix(usepagination): fix unstable callbacks
Closes #1549
2019-09-26 13:21:34 -06:00
ggascoigneandTanner Linsley 7ab6385839 TypeScript updates (#1521)
* TypeScript updates

I've found that trying to get solid TypeScript typings for this library
are a bit of a challenge.  The composable nature of the library means
that the types for the builtin functions are by their nature somewhat
minimal, and that the user needs to be able to extend those interfaces
to reflect the specific plugins that are in use.

With that in mind I propose something like this.

To get the best out of them, you then need to extend those interfaces
using declaration merging, see
https://www.typescriptlang.org/docs/handbook/declaration-merging.html

e.g.

```ts
declare module 'react-table-hooks' {
  export interface TableInstance<D = any>
    extends UseFiltersValues<D>,
      UsePaginationValues<D>,
      UseExpandedValues,
      UseGroupByValues {}

  export interface TableState<D = any>
    extends UsePaginationState,
      UseGroupByState,
      UseSortbyState<D>,
      UseFiltersState<D> {}
}
```

This also puts the ability to extend those types with any user defined
hooks completely in the users hands.

This gives the greatest flexibility, but I'll admit that it isn't
particularly obvious.  Perhaps a typescript readme and example is needed.

* fix useExpanded type

* fix module name

* fix typo

* address review feedback

* add IdType, update Filters definition
2019-09-20 09:37:45 -06:00
Tanner LinsleyandGitHub b8ed02cadc Update README.md 2019-09-17 15:44:02 -06:00
Tanner LinsleyandGitHub c3e917f13b Update README.md 2019-09-17 15:42:36 -06:00
tannerlinsley 7e6d719af4 docs(changelog): update changelog 2019-09-13 09:24:24 -06:00
tannerlinsley da678d0a61 Merge branch 'master' of https://github.com/react-tools/react-table 2019-09-13 09:22:09 -06:00
Tanner LinsleyandGitHub c3fe4c7fd8 Update README.md 2019-09-13 09:22:03 -06:00
118 changed files with 44614 additions and 1242 deletions
+11 -9
View File
@@ -1,7 +1,6 @@
---
name: Bug report
about: Create a report to help us improve
---
# Using v6?
@@ -10,13 +9,14 @@ v6 is now considered feature complete to its current abilities and limitations.
# Using v7?
Thanks for using the alpha version of React Table v7! We're very excited about it.
Thanks for using the beta version of React Table v7! We're very excited about it.
**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 '....'
@@ -32,15 +32,17 @@ Use a new [react-table codesandbox](https://codesandbox.io/s/m5lxzzpz69) to repr
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]
- 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]
- 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.
+4
View File
@@ -1,3 +1,7 @@
## 7.0.0-beta.0
- Massive changes to the entire project and library. Please consult the README and documentation for more information regarding these changes.
## 6.8.6
#### Fixes & Optimizations
+14 -9
View File
@@ -7,6 +7,9 @@ Hooks for building **lightweight, fast and extendable datagrids** 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>
<a href="https://bundlephobia.com/result?p=react-table@next" target="\_parent">
<img alt="" src="https://badgen.net/bundlephobia/minzip/react-table@next" />
</a>
<a href="https://npmjs.com/package/react-table" target="\_parent">
<img alt="" src="https://img.shields.io/npm/dm/react-table.svg" />
</a>
@@ -30,7 +33,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
## Features
- Lightweight (4kb - 11kb depending on features and tree-shaking)
- Lightweight (4kb - 9kb depending on features and tree-shaking)
- Headless (100% customizable, Bring-your-own-UI)
- Auto out of the box, fully controllable API
- Sorting (Multi and Stable)
@@ -40,6 +43,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
- Row Expansion
- Column Ordering
- Animatable
- Virtualizable
- Server-side/controlled data/state
- Extensible via hook-based plugin system
- <a href="https://medium.com/@tannerlinsley/why-i-wrote-react-table-and-the-problems-it-has-solved-for-nozzle-others-445c4e93d4a8#.axza4ixba" target="\_parent">"Why I wrote React Table and the problems it has solved for Nozzle.io"</a> by Tanner Linsley
@@ -48,11 +52,11 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
#### What is the current state of React Table?
React Table v7 is still under active development, and its API is still changing, albeit only slightly. For this reason, it is currently in an **alpha** release state. It's estimated that it will be out of alpha and into **beta** sometime during September 2019. It will then remain in beta for a short time before being released sometime in Q4 of 2019.
React Table v7 is still under active development, and its API is still changing, albeit only slightly. For this reason, it is currently in an **beta** release state. It's estimated that it will be fully released as a stable version sometime during October 2019.
#### Should I use v7@alpha in production?
#### Should I use v7@beta in production?
You can use it production as long as you lock in the alpha version in your package.json and also accept that the API will likely change before it's official release.
You can use it in production as long as you lock in the beta version in your package.json and also accept that there may be unlikely, but possible bug fixes and/or API changes before it's official release.
#### I'm still using v6, what should I do?
@@ -80,7 +84,7 @@ The differences between the 2 versions are incredibly massive. Unfortunately, I
**React Table v7** is being built and maintained by me, @tannerlinsley and I am always in need of more Patreon support to keep this project afloat. If you would like to contribute to my Patreon goal for v7 and beyond, [visit my Patreon and help me out!](https://patreon.com/tannerlinsley)
<table>
<tbody>
<tbody {...getTableBodyProps()}>
<tr>
<td align="center" valign="middle">
<a href="https://patreon.com/tannerlinsley" target="_blank">
@@ -102,7 +106,7 @@ The differences between the 2 versions are incredibly massive. Unfortunately, I
</table>
<table>
<tbody>
<tbody {...getTableBodyProps()}>
<tr>
<td align="center" valign="middle">
<a href="https://patreon.com/tannerlinsley" target="_blank">
@@ -124,7 +128,7 @@ The differences between the 2 versions are incredibly massive. Unfortunately, I
</table>
<table>
<tbody>
<tbody {...getTableBodyProps()}>
<tr>
<td align="center" valign="middle">
<a href="https://patreon.com/tannerlinsley" target="_blank">
@@ -141,7 +145,7 @@ The differences between the 2 versions are incredibly massive. Unfortunately, I
</table>
<table>
<tbody>
<tbody {...getTableBodyProps()}>
<tr>
<td valign="top">
<a href="https://patreon.com/tannerlinsley">
@@ -157,7 +161,7 @@ The differences between the 2 versions are incredibly massive. Unfortunately, I
</table>
<table>
<tbody>
<tbody {...getTableBodyProps()}>
<tr>
<td valign="top">
<a href="https://patreon.com/tannerlinsley">
@@ -172,6 +176,7 @@ The differences between the 2 versions are incredibly massive. Unfortunately, I
<div>Dan Houle</div>
<div>David Pickut</div>
<div>Jordan Soltman</div>
<div>Robert Tajnšek</div>
</td>
</tr>
</tbody>
+127 -770
View File
@@ -15,6 +15,10 @@ React Table is essentially a compatible collection of **custom React hooks**:
- [`usePagination`](#usePagination)
- [`useRowSelect`](#useRowSelect)
- [`useRowState`](#useRowState)
- [`useColumnOrder`](#useColumnOrder)
- Layout Hooks
- [`useBlockLayout`](#useBlockLayout)
- [`useAbsoluteLayout`](#useAbsoluteLayout)
- Utility Hooks
- [`useTableState`](#useTableState)
- 3rd Party Plugin Hooks
@@ -151,6 +155,20 @@ The following options are supported on any column object you can pass to `column
- Receives the table instance and cell model as props
- Must return valid JSX
- This function (or component) is primarily used for formatting the column value, eg. If your column accessor returns a date object, you can use a `Cell` function to format that date to a readable format.
- `width: Int`
- Optional
- Defaults to `150`
- Specifies the width for the column (when using non-table-element layouts)
- `minWidth: Int`
- Optional
- Defaults to `0`
- Specifies the minimum width for the column (when using non-table-element layouts)
- Specifically useful when using plugin hooks that allow the user to resize column widths
- `maxWidth: Int`
- Optional
- Defaults to `0`
- Specifies the maximum width for the column (when using non-table-element layouts)
- Specifically useful when using plugin hooks that allow the user to resize column widths
### Instance Properties
@@ -182,6 +200,10 @@ The following properties are available on the table instance returned from `useT
- **Required**
- This function is used to resolve any props needed for your table wrapper.
- Custom props may be passed. **NOTE: Custom props will override built-in table props, so be careful!**
- `getTableBodyProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for your table body wrapper.
- Custom props may be passed. **NOTE: Custom props will override built-in table body props, so be careful!**
- `prepareRow: Function(Row)`
- **Required**
- This function is responsible for lazily preparing a row for rendering. Any row that you intend to render in your table needs to be passed to this function **before every render**.
@@ -193,6 +215,8 @@ The following properties are available on the table instance returned from `useT
- `flatRows: Array<Row>`
- An array of all rows, including subRows which have been flattened into the order in which they were detected (depth first)
- This can be helpful in calculating total row counts that must include subRows
- `totalColumnsWidth: Int`
- This is the total width of all visible columns (when using non-table-element layouts)
- `setRowState: Function(rowPath, updater: Function | any) => void`
- This function can be used to update the internal state for any row.
- Pass it a valid `rowPath` array and `updater`. The `updater` may be a value or function, similar to `React.useState`'s usage.
@@ -228,6 +252,12 @@ The following properties are available on every `Column` object returned by the
- The entire table `instance` will be passed to the renderer with the addition of a `column` property, containing a reference to the column
- If `type` is a string, will render using the `column[type]` renderer. React Table ships with default `Header` renderers. Other renderers like `Filter` are available via hooks like `useFilters`.
- If a function or component is passed instead of a string, it will be be passed the table instance and column model as props and is expected to return any valid JSX.
- `totalLeft: Int`
- This is the total width in pixels of all columns to the left of this column
- Specifically useful when using plugin hooks that allow the user to resize column widths
- `totalWidth: Int`
- This is the total width in pixels for this column (if it is a leaf-column) or or all of it's sub-columns (if it is a column group)
- Specifically useful when using plugin hooks that allow the user to resize column widths
- `getHeaderProps: Function(?props)`
- **Required**
- This function is used to resolve any props needed for this column's header cell.
@@ -287,82 +317,8 @@ The following additional properties are available on every `Cell` object returne
### Example
```js
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
],
[]
)
const data = [
{
firstName: 'Tanner',
lastName: 'Linsley',
},
{
firstName: 'Shawn',
lastName: 'Wang',
},
{
firstName: 'Kent C.',
lastName: 'Dodds',
},
{
firstName: 'Ryan',
lastName: 'Florence',
},
]
return <MyTable columns={columns} data={data} />
}
function MyTable({ columns, data }) {
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
columns,
data,
})
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
)}
</tbody>
</table>
)
}
```
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/basic)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
# `useSortBy`
@@ -473,62 +429,8 @@ The following properties are available on every `Column` object returned by the
### Example
```js
function Table({ columns, data }) {
// Set some default sorting state
const state = useTableState({ sortBy: [{ id: 'firstName', desc: true }] })
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
{
columns,
data,
},
useSortBy // Use the sortBy hook
)
return (
<table {...getTableProps()}>
<thead>
{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.getSortByToggleProps())}>
{column.render('Header')}
<span>
{/* Add a sort direction indicator */}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
{/* Add a sort index indicator */}
<span>({column.isSorted ? column.sortedIndex + 1 : ''})</span>
</span>
</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})}
</tr>
)
)}
</tbody>
</table>
)
}
```
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/sorting)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting)
# `useFilters`
@@ -612,49 +514,8 @@ The following properties are available on every `Column` object returned by the
### Example
```js
// A great library for fuzzy filtering/sorting items
import matchSorter from 'match-sorter'
const state = useTableState({ filters: { firstName: 'tanner' } })
const filterTypes = React.useMemo(() => ({
// Add a new fuzzyText filter type.
fuzzyText: (rows, id, filterValue) => {
return matchSorter(rows, filterValue, { keys: [row => row[id] })
},
// Or, override the default text filter to use
// "startWith"
text: (rows, id, filterValue) => {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue !== undefined
? String(rowValue)
.toLowerCase()
.startsWith(String(filterValue).toLowerCase())
: true
})
}
}), [matchSorter])
// Override the default column filter to be our new `fuzzyText` filter type
const defaultColumn = React.useMemo(() => ({
filter: 'fuzzyText'
}))
const { rows } = useTable(
{
// state[0].groupBy === ['firstName']
state,
manualFilters: false,
disableFilters: false,
// Pass our custom filter types
filterTypes,
defaultColumn
},
useFilters
)
```
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
# `useGroupBy`
@@ -766,168 +627,8 @@ The following additional properties are available on every `Cell` object returne
### Example
```js
function Table({ columns, data }) {
const {
getTableProps,
headerGroups,
rows,
prepareRow,
state: [{ groupBy, expanded }],
} = useTable(
{
columns,
data,
},
useGroupBy,
useExpanded // useGroupBy would be pretty useless without useExpanded ;)
)
// 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()
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: ({ cell: { value } }) => `${value} Names`,
},
{
Header: 'Last Name',
accessor: 'lastName',
// Use another two-stage aggregator here to
// first count the UNIQUE values from the rows
// being aggregated, then sum those counts if
// they are aggregated further
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
// Aggregate the average age of visitors
aggregate: 'average',
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
// Aggregate the sum of all visits
aggregate: 'sum',
Aggregated: ({ cell: { value } }) => `${value} (total)`,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
// Use our custom roundedMedian aggregator
aggregate: roundedMedian,
Aggregated: ({ cell: { value } }) => `${value} (med)`,
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(10000), [])
return <Table columns={columns} data={data} />
}
```
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/grouping)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping)
# `useExpanded`
@@ -974,126 +675,8 @@ The following additional properties are available on every `row` object returned
### Example
```js
function Table({ columns: userColumns, data }) {
const {
getTableProps,
headerGroups,
rows,
prepareRow,
state: [{ expanded }],
} = useTable(
{
columns: userColumns,
data,
},
useExpanded // Use the useExpanded plugin hook
)
return (
<>
<pre>
<code>{JSON.stringify({ expanded }, 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>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)
)}
</tbody>
</table>
<br />
<div>Showing the first 20 results of {rows.length} rows</div>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
// Build our expander column
Header: () => null, // No header, please
id: 'expander', // Make sure it has an ID
Cell: ({ row }) =>
// Use the row.canExpand and row.getExpandedToggleProps prop getter
// to build the toggle for expanding a row
row.canExpand ? (
<span
{...row.getExpandedToggleProps({
style: {
// We can even use the row.depth property
// and paddingLeft to indicate the depth
// of the row
paddingLeft: `${row.depth * 2}rem`,
},
})}
>
{row.isExpanded ? '👇' : '👉'}
</span>
) : null,
},
{
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(5, 5, 5), [])
return <Table columns={columns} data={data} />
}
```
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/expanding)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/expanding)
# `usePagination`
@@ -1168,178 +751,12 @@ The following values are provided to the table `instance`:
### Example
```js
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>
)
}
```
- Basic Pagination
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination)
- Controlled Pagination
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination)
# `useTokenPagination (Coming Soon)`
@@ -1403,123 +820,8 @@ The following additional properties are available on every **prepared** `row` ob
### Example
```js
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
rows,
prepareRow,
state: [{ selectedRows }],
} = useTable(
{
columns,
data,
},
useRowSelect
)
// Render the UI for your table
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)
)}
</tbody>
</table>
<p>Selected Rows: {selectedRows.length}</p>
<pre>
<code>{JSON.stringify({ selectedRows }, null, 2)}</code>
</pre>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
{
Header: 'Name',
columns: [
{
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(10), [])
return <Table columns={columns} data={data} />
}
```
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/row-selection)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-selection)
# `useRowState`
@@ -1575,6 +877,76 @@ The following additional properties are available on every `Cell` object returne
- Use this function to programmatically update the state of a cell.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
# `useBlocklayout`
- Plugin Hook
- Optional
`useBlocklayout` is a plugin hook that adds support for headers and cells to be rendered as `inline-block` `div`s (or other non-table elements) with explicit `width`. Similar to the `useAbsoluteLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
**NOTE:** Although no additional options are needed, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
### Row Properties
- `getRowProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows
### Cell Properties
- `getCellProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows cells
### Header Properties
- `getHeaderProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/block-layout)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/block-layout)
# `useAbsoluteLayout`
- Plugin Hook
- Optional
`useAbsoluteLayout` is a plugin hook that adds support for headers and cells to be rendered as absolutely positioned `div`s (or other non-table elements) with explicit `width`. Similar to the `useBlockLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
**NOTE:** Although no additional options are needed, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
### Instance Properties
- `getTableBodyProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for the table body
### Row Properties
- `getRowProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows
### Cell Properties
- `getCellProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for rows cells
### Header Properties
- `getHeaderProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/absolute-layout)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/absolute-layout)
# `useColumnOrder`
- Plugin Hook
@@ -1596,9 +968,13 @@ The following options are supported via the main options object passed to `useTa
The following values are provided to the table `instance`:
- `setColumnOrder: Function(updater: Function | Array<ColumnID>) => void`
- Use this function to programmatically update the columnOrder.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
# `useTableState`
- Optional
@@ -1632,7 +1008,7 @@ The following options are supported via the main options object passed to `useTa
- Optional
- Inspired by Kent C. Dodd's [State Reducer Pattern](https://kentcdodds.com/blog/the-state-reducer-pattern-with-react-hooks)
- With every `setState` call to a table state (even internally), this reducer is called and is allowed to modify the final state object for updating.
- It is passed the `oldState`, the `newState`, and an action `type`.
- It is passed the `oldState`, the `newState`, and an optional action `type`.
- `useState`
- Optional
- Defaults to `React.useState`
@@ -1653,30 +1029,11 @@ The following options are supported via the main options object passed to `useTa
- This function signature is **almost** (see next point) identical to the functional API exposed by `React.setState`. It is passed the previous state and is expected to return a new version of the state.
- **NOTE: `updater` must be a function. Passing a replacement object is not supported as it is with React.useState**
- `type: String`
- Optional
- The [action type](TODO) corresponding to what action being taken against the state.
### Example
```js
export default function MyTable({ manualPageIndex }) {
// This is the initial state for our table
const initialState = { pageSize: 10, pageIndex: 0 }
// Here, we can override the pageIndex
// regardless of the internal table state
const overrides = React.useMemo(() => ({
pageIndex: manualPageIndex,
}))
const state = useTableState(initialState, overrides)
// You can use effects to observe changes to the state
React.useEffect(() => {
console.log('Page Size Changed!', initialState.pageSize)
}, [initialState.pageSize])
const { rows } = useTable({
state,
})
}
```
- As used in Controlled Pagination
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
+20 -15
View File
@@ -2,49 +2,54 @@
- **Simple** - All of these examples use automatic state management, meaning, they don't hoist any state out of the table or manually control anything. Start here for understanding the basics about how to build your table UI.
- Basic
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/basic)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/basic)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
- Sorting
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/sorting)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/sorting)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting)
- Filtering
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
- Grouping
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/grouping)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/grouping)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping)
- Pagination
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination)
- Row Selection
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/row-selection)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/row-selection)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-selection)
- Expanding
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/expanding)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/expanding)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/expanding)
- Sub Components
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/sub-components)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/sub-components)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sub-components)
- Editable Data
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/editable-data)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/editable-data)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-data)
- Column Ordering
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
- **Complex**
- The "Kitchen Sink"
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- **Controlled via `useTableState`** - These examples are more advanced because they demonstrate how to manually control and respond to the state of the table using the `useTableState` hook.
- Pagination (Controlled)
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- [Open in CodeSandobx](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- **UI** - These examples demonstrate how to use React Table with your favorite UI libraries or tools!
- **UI & Rendering** - These examples demonstrate how to use React Table with your favorite UI libraries or tools!
- Virtualized Rows (React-Window)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/virtualized-rows)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/virtualized-rows)
- Animated (Framer-Motion)
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
- Material-UI
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/material-UI-components)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/material-UI-components)
- [ ] Styled-Components
- [ ] CSS
- [ ] Material-UI
- [ ] Bootstrap
- Want to write one of these examples or add another? [Submit a PR!](https://github.com/tannerlinsley/react-table/compare)
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+6
View File
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/absolute-layout)
- `yarn` and `yarn start` to run and edit the example
+35
View File
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "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"
}
+166
View File
@@ -0,0 +1,166 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useAbsoluteLayout } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
* {
box-sizing: border-box;
}
.table {
border: 1px solid #000;
max-width: 700px;
overflow-x: auto;
}
.header {
font-weight: bold;
}
.rows {
overflow-y: auto;
}
.row {
border-bottom: 1px solid #000;
height: 32px;
&.body {
:last-child {
border: 0;
}
}
}
.cell {
height: 100%;
line-height: 30px;
border-right: 1px solid #000;
padding-left: 5px;
:last-child {
border: 0;
}
}
`
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const defaultColumn = React.useMemo(
() => ({
width: 150,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
defaultColumn,
},
useAbsoluteLayout
)
// Render the UI for your table
return (
<div {...getTableProps()} className="table">
<div>
{headerGroups.map(headerGroup => (
<div
{...headerGroup.getHeaderGroupProps()}
className="row header-group"
>
{headerGroup.headers.map(column => (
<div {...column.getHeaderProps()} className="cell header">
{column.render('Header')}
</div>
))}
</div>
))}
</div>
<div className="rows" {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
<div {...row.getRowProps()} className="row body">
{row.cells.map(cell => {
return (
<div {...cell.getCellProps()} className="cell">
{cell.render('Cell')}
</div>
)
})}
</div>
)
)}
</div>
</div>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
width: 50,
},
{
Header: 'Visits',
accessor: 'visits',
width: 60,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(20), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
+9
View File
@@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+12
View File
@@ -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();
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
@@ -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
+2 -1
View File
@@ -202,6 +202,7 @@ function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
flatColumns,
@@ -264,7 +265,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
<AnimatePresence>
{rows.slice(0, 10).map(
(row, i) =>
+8 -2
View File
@@ -35,7 +35,13 @@ const Styles = styled.div`
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})
@@ -52,7 +58,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+6
View File
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/block-layout)
- `yarn` and `yarn start` to run and edit the example
+35
View File
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "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

+38
View File
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+149
View File
@@ -0,0 +1,149 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useBlockLayout } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
.table {
display: inline-block;
border-spacing: 0;
border: 1px solid black;
.tr {
:last-child {
.td {
border-bottom: 0;
}
}
}
.th,
.td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
`
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const defaultColumn = React.useMemo(
() => ({
width: 150,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
defaultColumn,
},
useBlockLayout
)
// Render the UI for your table
return (
<div {...getTableProps()} className="table">
<div>
{headerGroups.map(headerGroup => (
<div {...headerGroup.getHeaderGroupProps()} className="tr">
{headerGroup.headers.map(column => (
<div {...column.getHeaderProps()} className="th">
{column.render('Header')}
</div>
))}
</div>
))}
</div>
<div {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
<div {...row.getRowProps()} className="tr">
{row.cells.map(cell => {
return (
<div {...cell.getCellProps()} className="td">
{cell.render('Cell')}
</div>
)
})}
</div>
)
)}
</div>
</div>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
width: 50,
},
{
Header: 'Visits',
accessor: 'visits',
width: 60,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(20), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
+9
View File
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+12
View File
@@ -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()
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
+135
View File
@@ -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
+2 -1
View File
@@ -47,6 +47,7 @@ function shuffle(arr) {
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
flatColumns,
@@ -78,7 +79,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.slice(0, 10).map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -83,6 +83,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
// Otherwise, nothing is different here.
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
@@ -124,7 +125,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{page.map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -36,6 +36,7 @@ const Styles = styled.div`
function Table({ columns: userColumns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
@@ -60,7 +61,7 @@ function Table({ columns: userColumns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
+9 -2
View File
@@ -210,7 +210,14 @@ function Table({ columns, data }) {
[]
)
const { getTableProps, headerGroups, rows, prepareRow, state } = useTable(
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
state,
} = useTable(
{
columns,
data,
@@ -245,7 +252,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{firstPageRows.map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -36,6 +36,7 @@ const Styles = styled.div`
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
@@ -77,7 +78,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{firstPageRows.map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -270,6 +270,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we'll use page,
@@ -344,7 +345,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{page.map(
row =>
prepareRow(row) || (
+2 -1
View File
@@ -270,6 +270,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we'll use page,
@@ -344,7 +345,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{page.map(
row =>
prepareRow(row) || (
+3
View File
@@ -0,0 +1,3 @@
{
"presets": ["react-app"]
}
+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/material-UI-components)
- `yarn` and `yarn start` to run and edit the example
@@ -0,0 +1,36 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"@material-ui/core": "^4.4.3",
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next"
},
"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",
"eslint-config-prettier": "^6.3.0"
},
"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"
}
+112
View File
@@ -0,0 +1,112 @@
import React from 'react'
import CssBaseline from '@material-ui/core/CssBaseline'
import MaUTable from '@material-ui/core/Table'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import { useTable } from 'react-table'
import makeData from './makeData'
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableHeaderProps,
headerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})
// Render the UI for your table
return (
<MaUTable {...getTableProps()}>
<TableHead>
{headerGroups.map(headerGroup => (
<TableRow {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<TableCell {...column.getHeaderProps()}>
{column.render('Header')}
</TableCell>
))}
</TableRow>
))}
</TableHead>
<TableBody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<TableCell {...cell.getCellProps()}>
{cell.render('Cell')}
</TableCell>
)
})}
</TableRow>
)
)}
</TableBody>
</MaUTable>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(20), [])
return (
<div>
<CssBaseline />
<Table columns={columns} data={data} />
</div>
)
}
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
+5 -7
View File
@@ -54,15 +54,13 @@ function Table({
const [{ pageIndex, pageSize }] = tableState
// Listen for changes in pagination and use the state to fetch our new data
React.useEffect(
() => {
fetchData({ pageIndex, pageSize })
},
[fetchData, pageIndex, pageSize]
)
React.useEffect(() => {
fetchData({ pageIndex, pageSize })
}, [fetchData, pageIndex, pageSize])
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
@@ -116,7 +114,7 @@ function Table({
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{page.map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -43,6 +43,7 @@ function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we'll use page,
@@ -95,7 +96,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{page.map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -37,6 +37,7 @@ function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
@@ -62,7 +63,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
+2 -2
View File
@@ -18,7 +18,7 @@ Next, add the `useSortBy` hook to your `useTable` hook and add the necessary UI
```diff
function MyTable() {
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable(
{
data,
columns,
@@ -43,7 +43,7 @@ function MyTable() {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
+8 -2
View File
@@ -34,7 +34,13 @@ const Styles = styled.div`
`
function Table({ columns, data }) {
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
@@ -70,7 +76,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{firstPageRows.map(
(row, i) =>
prepareRow(row) || (
+2 -1
View File
@@ -39,6 +39,7 @@ const Styles = styled.div`
function Table({ columns: userColumns, data, renderRowSubComponent }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
@@ -68,7 +69,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+6
View File
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/virtualized-rows)
- `yarn` and `yarn start` to run and edit the example
+36
View File
@@ -0,0 +1,36 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"react-window": "^1.8.5",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -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"
}
+175
View File
@@ -0,0 +1,175 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useBlockLayout } from 'react-table'
import { FixedSizeList } from 'react-window'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
.table {
display: inline-block;
border-spacing: 0;
border: 1px solid black;
.tr {
:last-child {
.td {
border-bottom: 0;
}
}
}
.th,
.td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
}
`
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const defaultColumn = React.useMemo(
() => ({
width: 150,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
totalColumnsWidth,
prepareRow,
} = useTable(
{
columns,
data,
defaultColumn,
},
useBlockLayout
)
const RenderRow = React.useCallback(
({ index, style }) => {
const row = rows[index]
prepareRow(row)
return (
<div
{...row.getRowProps({
style,
})}
className="tr"
>
{row.cells.map(cell => {
return (
<div {...cell.getCellProps()} className="td">
{cell.render('Cell')}
</div>
)
})}
</div>
)
},
[prepareRow, rows]
)
console.log(headerGroups)
// Render the UI for your table
return (
<div {...getTableProps()} className="table">
<div>
{headerGroups.map(headerGroup => (
<div {...headerGroup.getHeaderGroupProps()} className="tr">
{headerGroup.headers.map(column => (
<div {...column.getHeaderProps()} className="th">
{column.render('Header')}
</div>
))}
</div>
))}
</div>
<div {...getTableBodyProps()}>
<FixedSizeList
height={400}
itemCount={rows.length}
itemSize={35}
width={totalColumnsWidth}
>
{RenderRow}
</FixedSizeList>
</div>
</div>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Row Index',
accessor: (row, i) => i,
},
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
width: 50,
},
{
Header: 'Visits',
accessor: 'visits',
width: 60,
},
{
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)
})
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+12
View File
@@ -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()
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
@@ -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
Vendored
+281 -177
View File
@@ -1,184 +1,288 @@
import { Dispatch, SetStateAction, ReactNode } from 'react';
declare module 'react-table' {
export interface Cell<D> {
render: (type: string) => any;
getCellProps: () => any;
column: Column<D>;
row: Row<D>;
state: any;
value: any;
import { ReactNode, useState } from 'react'
type StringKey<D> = Extract<keyof D, string>
type IdType<D> = StringKey<D> | string
type SortingRule<D> = {
id: IdType<D>
desc: boolean
}
export type SortingRules<D> = SortingRule<D>[]
export type SortByFn = (a: any, b: any, desc: boolean) => 0 | 1 | -1
export type Filters<D> = Record<IdType<D>, string>
export interface Cell<D = {}> extends TableInstance<D> {
cell: { value: any }
column: Column<D>
row: Row<D>
render: (type: 'Cell' | 'Aggregated', userProps?: any) => any
isGrouped?: boolean
isAggregated?: boolean
isRepeatedValue?: boolean
getCellProps: () => any
}
export interface Row<D = {}> {
index: number
cells: Cell<D>[]
getRowProps: (userProps?: any) => any
original: D
path: any[]
values: any[]
depth: number
}
export interface UseExpandedRow<D = {}> {
subRows?: D[]
groupByID?: string | number
toggleExpanded?: () => any
isExpanded?: boolean
isAggregated?: boolean
}
export type AccessorFn<D> = (
originalRow: D,
index: number,
sub: {
subRows: [D]
depth: number
data: [D]
}
) => unknown
export interface Row<D> {
index: number;
cells: Cell<D>[];
getRowProps: () => any;
original: any;
export interface HeaderColumn<D> {
/**
* This string/function is used to build the data model for your column.
*/
accessor: IdType<D> | AccessorFn<D>
Header?: ReactNode | ((props: TableInstance<D>) => ReactNode)
Filter?: ReactNode | ((props: TableInstance<D>) => ReactNode)
Cell?: ReactNode | ((cell: Cell<D>) => ReactNode)
/**
* This is the unique ID for the column. It is used by reference in things like sorting, grouping, filtering etc.
*/
id?: IdType<D>
minWidth?: string | number
maxWidth?: string | number
width?: string | number
disableSorting?: boolean
canSortBy?: boolean
sortByFn?: SortByFn
defaultSortDesc?: boolean
isAggregated?: any
}
export interface Column<D> extends HeaderColumn<D> {
show?: boolean | ((instance: TableInstance<D>) => boolean)
columns?: Column<D>[]
}
export type Page<D = {}> = Row<D>[]
export interface EnhancedColumn<D>
extends Omit<Column<D>, 'columns'>,
TableInstance<D> {
id: IdType<D>
column: Column<D>
render: (type: 'Header' | 'Filter', userProps?: any) => any
getHeaderProps: (userProps?: any) => any
getSortByToggleProps: (userProps?: any) => any
isSorted: boolean
isSortedDesc: boolean
sortedIndex: number
isVisible: boolean
canSort?: boolean
}
export interface HeaderGroup<D = {}> {
headers: EnhancedColumn<D>[]
getHeaderGroupProps: (userProps?: any) => any
}
export interface Hooks {
columnsBeforeHeaderGroups: any[]
columnsBeforeHeaderGroupsDeps: any[]
useMain: any[]
useColumns: any[]
useHeaders: any[]
useHeaderGroups: any[]
useRows: any[]
prepareRow: any[]
getTableProps: any[]
getRowProps: any[]
getHeaderGroupProps: any[]
getHeaderProps: any[]
getCellProps: any[]
}
export interface RowsProps {
subRowsKey: string
}
export interface FiltersProps {
filterFn: () => void
manualFilters: boolean
disableFilters: boolean
setFilter: () => any
setAllFilters: () => any
}
export interface UsePaginationState {
pageIndex: number
pageSize: number
pageCount: number
rowCount: number
}
export interface UsePaginationValues<D = {}> {
page: Page<D>
pageIndex: number // yes, this is on instance and state
pageSize: number // yes, this is on instance and state
canPreviousPage: boolean
canNextPage: boolean
nextPage: () => any
previousPage: () => any
setPageSize: (size: number) => any
pageOptions: any[]
manualPagination: boolean
paginateExpandedRows: boolean
disablePageResetOnDataChange: boolean
pageCount: number
gotoPage: (page: number) => any
}
export interface UseFiltersState<D> {
filters?: Filters<D>
}
export interface UseFiltersValues<D> {
setFilter: (columnID: keyof D, value: string) => void
setAllFilters: (values: Filters<D>) => void
disableFilters: boolean
}
export interface UseGroupByValues {
groupByFn: any
manualGroupBy: boolean
disableGrouping: boolean
aggregations: any
}
export interface UseGroupByState {
groupBy: string[]
isAggregated?: boolean
}
export interface UseExpandedValues {
toggleExpanded?: () => any
}
export interface UseSortbyOptions {
sortByFn?: SortByFn
manualSorting?: boolean
disableSorting?: boolean
defaultSortDesc?: boolean
disableMultiSort?: boolean
}
export interface UseSortbyState<D> {
sortBy?: SortingRules<D>
}
export interface TableInstance<D = {}> extends TableOptions<D> {
hooks: Hooks
rows: Row<D>[]
columns: EnhancedColumn<D>[]
headerGroups: HeaderGroup<D>[]
headers: HeaderGroup<D>[]
getTableProps: (userProps?: any) => any
getRowProps: (userProps?: any) => any
prepareRow: (row: Row<D>) => any
}
export interface TableOptions<D = {}> {
data: D[]
columns: HeaderColumn<D>[]
state: State<D>
debug?: boolean
loading: boolean
defaultColumn?: Partial<Column<D>>
}
// The empty definition of TableState is not an error. It provides a definition
// for the state, that can then be extended in the users code.
//
// e.g.
//
// export interface TableState<D = {}}>
// extends UsePaginationState,
// UseGroupByState,
// UseSortbyState<D>,
// UseFiltersState<D> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TableState<D = {}> {}
export type SetState<D> = (
updater: (old: TableState<D>) => TableState<D>,
actions: any
) => void
export type State<D> = [TableState<D>, SetState<D>]
export function useTable<D = {}>(
props: TableOptions<D>,
...plugins: any[]
): TableInstance<D>
export function useFilters<D = {}>(
props: TableOptions<D>
): TableOptions<D> & {
rows: Row<D>[]
}
export function useSortBy<D = {}>(
props: TableOptions<D>
): TableOptions<D> & {
rows: Row<D>[]
}
export function useGroupBy<D = {}>(
props: TableOptions<D>
): TableOptions<D> & { rows: Row<D>[] }
export function usePagination<D = {}>(
props: TableOptions<D>
): UsePaginationValues<D>
export function useExpanded<D = {}>(
props: TableOptions<D>
): TableOptions<D> & {
toggleExpandedByPath: () => any
expandedDepth: []
rows: Row<D>[]
}
export function useTableState<D = {}>(
initialState?: Partial<TableState<D>>,
overriddenState?: Partial<TableState<D>>,
options?: {
reducer?: (
oldState: TableState<D>,
newState: TableState<D>,
type: string
) => any
useState?: typeof useState
}
): State<D>
export interface HeaderColumn<D, A extends keyof D = never> {
/**
* This string/function is used to build the data model for your column.
*/
accessor: A | ((originalRow: D) => string);
Header?: string | ((props: TableInstance<D>) => ReactNode);
Filter?: string | ((props: TableInstance<D>) => ReactNode);
Cell?: string | ((cell: Cell<D>) => ReactNode);
export const actions: Record<string, string>
/**
* This is the unique ID for the column. It is used by reference in things like sorting, grouping, filtering etc.
*/
id?: string | number;
minWidth?: string | number;
maxWidth?: string | number;
width?: string | number;
canSortBy?: boolean;
sortByFn?: (a: any, b: any, desc: boolean) => 0 | 1 | -1;
defaultSortDesc?: boolean;
}
export function addActions(...actions: string[]): void
export interface Column<D, A extends keyof D = never> extends HeaderColumn<D, A> {
id: string | number;
}
export type Page<D> = Row<D>[];
export interface EnhancedColumn<D, A extends keyof D = never> extends Column<D, A> {
render: (type: string) => any;
getHeaderProps: (userProps?: any) => any;
getSortByToggleProps: (userProps?: any) => any;
sorted: boolean;
sortedDesc: boolean;
sortedIndex: number;
}
export type HeaderGroup<D, A extends keyof D = never> = {
headers: EnhancedColumn<D, A>[];
getRowProps: (userProps?: any) => any;
};
export interface Hooks<D> {
beforeRender: [];
columns: [];
headerGroups: [];
headers: [];
rows: Row<D>[];
row: [];
renderableRows: [];
getTableProps: [];
getRowProps: [];
getHeaderRowProps: [];
getHeaderProps: [];
getCellProps: [];
}
export interface TableInstance<D>
extends TableOptions<D>,
UseRowsValues<D>,
UseFiltersValues,
UsePaginationValues<D>,
UseColumnsValues<D> {
hooks: Hooks<D>;
rows: Row<D>[];
columns: EnhancedColumn<D>[];
getTableProps: (userProps?: any) => any;
getRowProps: (userProps?: any) => any;
prepareRow: (row: Row<D>) => any;
getSelectRowToggleProps: (userProps?: any) => any;
toggleSelectAll: (forcedState: boolean) => any;
}
export interface TableOptions<D> {
data: D[];
columns: HeaderColumn<D>[];
state?: [any, Dispatch<SetStateAction<any>>];
debug?: boolean;
sortByFn?: (a: any, b: any, desc: boolean) => 0 | 1 | -1;
manualSorting?: boolean;
disableSorting?: boolean;
defaultSortDesc?: boolean;
disableMultiSort?: boolean;
}
export interface RowsProps {
subRowsKey: string;
}
export interface FiltersProps {
filterFn: () => void;
manualFilters: boolean;
disableFilters: boolean;
setFilter: () => any;
setAllFilters: () => any;
}
export interface UsePaginationValues<D> {
nextPage: () => any;
previousPage: () => any;
setPageSize: (size: number) => any;
gotoPage: (page: number) => any;
canPreviousPage: boolean;
canNextPage: boolean;
page: Page<D>;
pageOptions: [];
}
export interface UseRowsValues<D> {
rows: Row<D>[];
}
export interface UseColumnsValues<D> {
columns: EnhancedColumn<D>[];
headerGroups: HeaderGroup<D>[];
headers: EnhancedColumn<D>[];
}
export interface UseFiltersValues {
setFilter: () => any;
setAllFilters: () => any;
}
export function useTable<D>(props: TableOptions<D>, ...plugins: any[]): TableInstance<D>;
export function useColumns<D>(props: TableOptions<D>): TableOptions<D> & UseColumnsValues<D>;
export function useRows<D>(props: TableOptions<D>): TableOptions<D> & UseRowsValues<D>;
export function useFilters<D>(
props: TableOptions<D>,
): TableOptions<D> & {
rows: Row<D>[];
};
export function useSortBy<D>(
props: TableOptions<D>,
): TableOptions<D> & {
rows: Row<D>[];
};
export function useGroupBy<D>(props: TableOptions<D>): TableOptions<D> & { rows: Row<D>[] };
export function usePagination<D>(props: TableOptions<D>): UsePaginationValues<D>;
export function useFlexLayout<D>(props: TableOptions<D>): TableOptions<D>;
export function useExpanded<D>(
props: TableOptions<D>,
): TableOptions<D> & {
toggleExpandedByPath: () => any;
expandedDepth: [];
rows: [];
};
export function useTableState(
initialState?: any,
overriddenState?: any,
options?: {
reducer?: (oldState: any, newState: any, type: string) => any;
useState?: [any, Dispatch<SetStateAction<any>>];
},
): any;
export const actions: any;
}
export const defaultState: Record<string, any>
}
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-beta.0",
"version": "7.0.0-beta.5",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
@@ -17,6 +17,7 @@
"main": "dist/index.js",
"module": "dist/index.es.js",
"jsnext:main": "dist/index.es.js",
"sideEffects": false,
"scripts": {
"commit": "git add . && git-cz",
"test": "is-ci 'test:ci' 'test:dev'",
@@ -27,7 +28,7 @@
"prepare": "yarn build",
"release": "yarn publish",
"releaseNext": "yarn publish --tag next",
"format": "prettier ./src/**/*.{md,js,jsx,tsx} --write"
"format": "prettier {src,src/**,examples/*/src,examples/*/src/**}/*.{md,js,jsx,tsx} --write"
},
"files": [
"CHANGELOG.md",
@@ -90,7 +91,7 @@
"rollup-plugin-commonjs": "^9.1.3",
"rollup-plugin-node-resolve": "^4.0.0",
"rollup-plugin-peer-deps-external": "^2.2.0",
"rollup-plugin-uglify": "^6.0.2",
"rollup-plugin-terser": "^5.1.2",
"snapshot-diff": "^0.5.2"
},
"config": {
+3 -16
View File
@@ -2,7 +2,7 @@ import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import resolve from 'rollup-plugin-node-resolve'
import { uglify } from 'rollup-plugin-uglify'
import { terser } from 'rollup-plugin-terser'
import pkg from './package.json'
@@ -14,28 +14,15 @@ export default [
format: 'cjs',
sourcemap: true,
},
plugins: [
external(),
babel({
exclude: 'node_modules/**',
}),
resolve(),
commonjs(),
uglify(),
],
plugins: [external(), babel(), resolve(), commonjs(), terser()],
},
{
input: 'src/index.js',
external: Object.keys(pkg.peerDependencies),
output: {
file: pkg.module,
format: 'es',
sourcemap: true,
},
plugins: [
babel({
exclude: ['/**/node_modules/**'],
}),
],
plugins: [external(), babel()],
},
]
-5
View File
@@ -5,11 +5,6 @@ export { actions, types }
export const addActions = (...acts) => {
acts.forEach(action => {
if (actions[action]) {
throw new Error(
`An React Table action type called ${action} has already been registered!`
)
}
// Action values are formatted this way to discourage
// you (the dev) from interacting with them in any way
// other than importing `{ actions } from 'react-table'`
@@ -63,7 +63,9 @@ exports[`renders a basic table 1`] = `
</th>
</tr>
</thead>
<tbody>
<tbody
class=""
>
<tr
class=""
>
+8 -2
View File
@@ -31,7 +31,13 @@ const data = [
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({
columns,
data,
})
@@ -48,7 +54,7 @@ function Table({ columns, data }) {
</tr>
))}
</thead>
<tbody>
<tbody {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
+45 -3
View File
@@ -70,6 +70,7 @@ export const useTable = (props, ...plugins) => {
useRows: [],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getRowProps: [],
getHeaderGroupProps: [],
getHeaderProps: [],
@@ -214,6 +215,8 @@ export const useTable = (props, ...plugins) => {
[]
)
calculateDimensions(instanceRef.current)
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.useMain')
instanceRef.current = applyHooks(
@@ -246,7 +249,7 @@ export const useTable = (props, ...plugins) => {
mergeProps(
{
key: ['header', column.id].join('_'),
colSpan: column.totalHeaderCount,
colSpan: column.totalVisibleHeaderCount,
},
applyPropHooks(
instanceRef.current.hooks.getHeaderProps,
@@ -306,7 +309,7 @@ export const useTable = (props, ...plugins) => {
// The prepareRow function is absolutely necessary and MUST be called on
// any rows the user wishes to be displayed.
instanceRef.current.prepareRow = row => {
instanceRef.current.prepareRow = React.useCallback(row => {
row.getRowProps = props =>
mergeProps(
{ key: ['row', ...row.path].join('_') },
@@ -366,7 +369,7 @@ export const useTable = (props, ...plugins) => {
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
}
}, [])
instanceRef.current.getTableProps = userProps =>
mergeProps(
@@ -377,5 +380,44 @@ export const useTable = (props, ...plugins) => {
userProps
)
instanceRef.current.getTableBodyProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableBodyProps,
instanceRef.current
),
userProps
)
return instanceRef.current
}
function calculateDimensions(instance) {
const { headers } = instance
instance.totalColumnsWidth = calculateHeaderWidths(headers)
}
function calculateHeaderWidths(headers, left = 0) {
let sumTotalWidth = 0
headers.forEach(header => {
let { headers: subHeaders } = header
header.totalLeft = left
if (subHeaders && subHeaders.length) {
header.totalWidth = calculateHeaderWidths(subHeaders, left)
} else {
header.totalWidth = Math.min(
Math.max(header.minWidth, header.width),
header.maxWidth
)
}
left += header.totalWidth
sumTotalWidth += header.totalWidth
})
return sumTotalWidth
}
-10
View File
@@ -1,7 +1,5 @@
import React from 'react'
//
import { types } from '../actions'
export const defaultState = {}
const defaultReducer = (old, newState) => newState
@@ -33,14 +31,6 @@ export const useTableState = (
const reducedSetState = React.useCallback(
(updater, type) => {
if (!types[type]) {
console.info({
stateUpdaterFn: updater,
actionType: type,
currentState: overriddenStateRef.current,
})
throw new Error('Detected an unknown table action! (Details Above)')
}
return setState(old => {
const newState = updater(old)
return reducer(old, newState, type)
+2
View File
@@ -11,4 +11,6 @@ export { usePagination } from './plugin-hooks/usePagination'
export { useRowSelect } from './plugin-hooks/useRowSelect'
export { useRowState } from './plugin-hooks/useRowState'
export { useColumnOrder } from './plugin-hooks/useColumnOrder'
export { useAbsoluteLayout } from './plugin-hooks/useAbsoluteLayout'
export { useBlockLayout } from './plugin-hooks/useBlockLayout'
export { actions, addActions } from './actions'
@@ -0,0 +1,206 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a table 1`] = `
<DocumentFragment>
<div
class="table"
>
<div>
<div
class="row"
style="position: relative; width: 1400px;"
>
<div
class="cell header"
colspan="2"
style="position: absolute; top: 0px; left: 0px; width: 550px;"
>
Name
</div>
<div
class="cell header"
colspan="4"
style="position: absolute; top: 0px; left: 550px; width: 850px;"
>
Info
</div>
</div>
<div
class="row"
style="position: relative; width: 1400px;"
>
<div
class="cell header"
colspan="1"
style="position: absolute; top: 0px; left: 0px; width: 250px;"
>
First Name
</div>
<div
class="cell header"
colspan="1"
style="position: absolute; top: 0px; left: 250px; width: 300px;"
>
Last Name
</div>
<div
class="cell header"
colspan="1"
style="position: absolute; top: 0px; left: 550px; width: 300px;"
>
Age
</div>
<div
class="cell header"
colspan="1"
style="position: absolute; top: 0px; left: 850px; width: 150px;"
>
Visits
</div>
<div
class="cell header"
colspan="1"
style="position: absolute; top: 0px; left: 1000px; width: 200px;"
>
Status
</div>
<div
class="cell header"
colspan="1"
style="position: absolute; top: 0px; left: 1200px; width: 200px;"
>
Profile Progress
</div>
</div>
</div>
<div
class=""
style="position: relative; width: 1400px;"
>
<div
class="row"
style="position: relative; width: 1400px;"
>
<div
class="cell"
style="position: absolute; top: 0px; left: 0px; width: 250px;"
>
firstName: tanner
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 250px; width: 300px;"
>
lastName: linsley
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 550px; width: 300px;"
>
age: 29
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 850px; width: 150px;"
>
visits: 100
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 1000px; width: 200px;"
>
status: In Relationship
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 1200px; width: 200px;"
>
progress: 50
</div>
</div>
<div
class="row"
style="position: relative; width: 1400px;"
>
<div
class="cell"
style="position: absolute; top: 0px; left: 0px; width: 250px;"
>
firstName: derek
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 250px; width: 300px;"
>
lastName: perkins
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 550px; width: 300px;"
>
age: 30
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 850px; width: 150px;"
>
visits: 40
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 1000px; width: 200px;"
>
status: Single
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 1200px; width: 200px;"
>
progress: 80
</div>
</div>
<div
class="row"
style="position: relative; width: 1400px;"
>
<div
class="cell"
style="position: absolute; top: 0px; left: 0px; width: 250px;"
>
firstName: joe
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 250px; width: 300px;"
>
lastName: bergevin
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 550px; width: 300px;"
>
age: 45
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 850px; width: 150px;"
>
visits: 20
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 1000px; width: 200px;"
>
status: Complicated
</div>
<div
class="cell"
style="position: absolute; top: 0px; left: 1200px; width: 200px;"
>
progress: 10
</div>
</div>
</div>
</div>
</DocumentFragment>
`;
@@ -0,0 +1,205 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a table 1`] = `
<DocumentFragment>
<div
class="table"
>
<div>
<div
class="row"
style="display: block; width: 1400px;"
>
<div
class="cell header"
colspan="2"
style="display: inline-block; box-sizing: border-box; width: 550px;"
>
Name
</div>
<div
class="cell header"
colspan="4"
style="display: inline-block; box-sizing: border-box; width: 850px;"
>
Info
</div>
</div>
<div
class="row"
style="display: block; width: 1400px;"
>
<div
class="cell header"
colspan="1"
style="display: inline-block; box-sizing: border-box; width: 250px;"
>
First Name
</div>
<div
class="cell header"
colspan="1"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
Last Name
</div>
<div
class="cell header"
colspan="1"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
Age
</div>
<div
class="cell header"
colspan="1"
style="display: inline-block; box-sizing: border-box; width: 150px;"
>
Visits
</div>
<div
class="cell header"
colspan="1"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
Status
</div>
<div
class="cell header"
colspan="1"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
Profile Progress
</div>
</div>
</div>
<div
class=""
>
<div
class="row"
style="display: block; width: 1400px;"
>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 250px;"
>
firstName: tanner
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
lastName: linsley
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
age: 29
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 150px;"
>
visits: 100
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
status: In Relationship
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
progress: 50
</div>
</div>
<div
class="row"
style="display: block; width: 1400px;"
>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 250px;"
>
firstName: derek
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
lastName: perkins
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
age: 30
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 150px;"
>
visits: 40
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
status: Single
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
progress: 80
</div>
</div>
<div
class="row"
style="display: block; width: 1400px;"
>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 250px;"
>
firstName: joe
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
lastName: bergevin
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 300px;"
>
age: 45
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 150px;"
>
visits: 20
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
status: Complicated
</div>
<div
class="cell"
style="display: inline-block; box-sizing: border-box; width: 200px;"
>
progress: 10
</div>
</div>
</div>
</div>
</DocumentFragment>
`;
@@ -19,7 +19,7 @@ Snapshot Diff:
</pre>
<table
class=""
@@ -82,10 +84,53 @@
@@ -86,10 +88,53 @@
<td
class=""
>
@@ -73,7 +73,7 @@ Snapshot Diff:
</span>
</td>
<td
@@ -115,10 +160,139 @@
@@ -119,10 +164,139 @@
</td>
<td
class=""
@@ -234,7 +234,7 @@ Snapshot Diff:
</code>
</pre>
<table
@@ -127,11 +128,54 @@
@@ -131,11 +132,54 @@
<td
class=""
>
@@ -289,7 +289,7 @@ Snapshot Diff:
</td>
<td
class=""
@@ -160,10 +204,139 @@
@@ -164,10 +208,139 @@
</td>
<td
class=""
@@ -450,7 +450,7 @@ Snapshot Diff:
</code>
</pre>
<table
@@ -171,11 +172,54 @@
@@ -175,11 +176,54 @@
<td
class=""
>
@@ -505,7 +505,7 @@ Snapshot Diff:
</td>
<td
class=""
@@ -204,10 +248,139 @@
@@ -208,10 +252,139 @@
</td>
<td
class=""
@@ -666,7 +666,7 @@ Snapshot Diff:
</code>
</pre>
<table
@@ -216,11 +217,11 @@
@@ -220,11 +221,11 @@
class=""
>
<span
@@ -679,7 +679,7 @@ Snapshot Diff:
<td
class=""
>
@@ -248,10 +249,30 @@
@@ -252,10 +253,30 @@
</td>
<td
class=""
@@ -734,7 +734,7 @@ Snapshot Diff:
</pre>
<table
class=""
@@ -88,140 +83,11 @@
@@ -92,140 +87,11 @@
class=""
>
<span
@@ -876,7 +876,7 @@ Snapshot Diff:
<td
class=""
>
@@ -249,417 +115,10 @@
@@ -253,417 +119,10 @@
</td>
<td
class=""

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