React Table uses React Hooks both internally and externally for almost all of its configuration and lifecycle management. Naturally, this is what allows React Table to be headless and lightweight while still having a concise and simple API.
React Table is essentially a compatible collection of custom React hooks:
useTable
is the primary hook used to build a React Table. It serves as the starting point for every option and every plugin hook that React Table supports. The options passed into useTable
are supplied to every plugin hook after it in the order they are supplied, eventually resulting a final instance
object that you can use to build your table UI and interact with the table's state.
const instance = useTable(
{
data: [...],
columns: [...],
},
useGroupBy,
useFilters,
useSortBy,
useExpanded,
usePagination
)
useTable
is called. A table instance is created.instance.state
is resolved from either a custom user state or an automatically generated one.instance.hooks
.instance.hook
.useTable
logic proceeds to run, each plugin hook type is used at a specific point in time with each individual hook function being executed the order it was registered.useTable
, which the developer then uses to construct their table.This multi-stage process is the secret sauce that allows React Table plugin hooks to work together and compose nicely, while not stepping on each others toes.
To dive deeper into plugins, see Plugins and the Plugin Guide
The order and usage of plugin hooks must follow The Laws of Hooks, just like any other custom hook. They must always be unconditionally called in the same order.
NOTE: In the event that you want to programmatically enable or disable plugin hooks, most of them provide options to disable their functionality, eg.
options.disableSorting
React Table relies on memoization to determine when state and side effects should update or be calculated. This means that every option you pass to useTable
should be memoized either via React.useMemo
(for objects) or React.useCallback
(for functions).
useTable
useTable
is the root hook for React Table. To use it, pass it with an options object with at least a columns
and rows
value, followed by any React Table compatible hooks you want to use.
The following options are supported via the main options object passed to useTable(options)
columns: Array<Column>
columns
arrays via the column's columns
key, eg. [{ Header: 'My Group', columns: [...] }]
data: Array<any>
state: TableStateTuple[stateObject, stateUpdater]
useTableState
for more information.useTableState()
instance if not defined.defaultColumn: Object
{}
{ ...defaultColumn, ...userColumn }
useFilters
plugin hook, add a default Filter
renderer for every column, eg.{ Filter: MyDefaultFilterComponent }
initialRowStateKey: String
initialState
rowState
for adata
array.row[initialRowStateKey]
is falsey, {}
will be used instead.getSubRows: Function(row, relativeIndex) => Rows[]
(row) => row.subRows || []
subRows
property on the row, or an empty array if that is not found.getRowID: Function(row, relativeIndex) => string
path
property.(row, relativeIndex) => relativeIndex
index
of the row within it's original array.debug: Bool
false
column
OptionsThe following options are supported on any column object you can pass to columns
.
accessor: String | Function
firstName
then its value would be read from row['firstName']
. You can also specify deeply nested values with accessors like info.hobbies
or even address[0].street
row => row.firstName
, then its value would be determined by passing the row to this function and using the resulting value.id: String
accessor
is a functioncolumns: Array<Column>
show: Boolean | Function
true
false
, the column will be hidden.function
, it will be called with the current table instance and can then return true
or false
.Header: String | Function | React.Component => JSX
() => null
Header
function to dynamically format the header using any table or column state.Cell: Function | React.Component => JSX
({ cell: { value } }) => String(value)
Cell
function to format that date to a readable format.width: Int
150
minWidth: Int
0
maxWidth: Int
0
The following properties are available on the table instance returned from useTable
columns: Array<Column>
flatColumns: Array<Column>
headerGroups: Array<HeaderGroup>
headers: Array<Column>
flatHeaders[] Array<Column>
rows: Array<Row>
data
array and columns
passed into the table optionsgetTableProps: Function(?props)
getTableBodyProps: Function(?props)
prepareRow: Function(Row)
rowPaths: Array<string>
path
of every original row in the table. eg. If a row has a path of [0, 3, 2]
, its stringified path would be 0.3.2
.useRowSelect
to manage row selection statedata
array will have a path in this array. Rows created by useGroupBy
's aggregations and grouping are not included in this array, since they do not reference an original data row.flatRows: Array<Row>
totalColumnsWidth: Int
setRowState: Function(rowPath, updater: Function | any) => void
rowPath
array and updater
. The updater
may be a value or function, similar to React.useState
's usage.updater
is a function, it will be passed the previous valuesetCellState: Function(rowPath, columnID, updater: Function | any) => void
rowPath
array, columnID
and updater
. The updater
may be a value or function, similar to React.useState
's usage.updater
is a function, it will be passed the previous valueThe following additional properties are available on every headerGroup
object returned by the table instance.
headers: Array<Column>
getHeaderGroupProps: Function(?props)
getHeaderGroupProps
hook to extend its functionality.The following properties are available on every Column
object returned by the table instance.
id: String
accessor
or the column's hard-coded id
propertyisVisible: Boolean
show
propertyrender: Function(type: String | Function | Component, ?props)
instance
will be passed to the renderer with the addition of a column
property, containing a reference to the columntype
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
.totalLeft: Int
totalWidth: Int
getHeaderProps: Function(?props)
getHeaderProps
hook to extend its functionality.The following additional properties are available on every row
object returned by the table instance.
cells: Array<Cell>
Cell
objects containing properties and functions specific to the row and column it belongs to.values: Object<columnID: any>
{ firstName: 'Tanner', lastName: 'Linsley' }
getRowProps: Function(?props)
getRowProps
hook to extend its functionality.index: Int
data
array that was passed to useTable
. If this row is a subRow, it is the original index within the parent row's subRows arrayoriginal: Object
data
array that was used to materialize this row.path: Array<string>
[3, 1, 0]
would mean that it is the first subRow of a parent that is the second subRow of a parent that is the fourth row in the original data
array.useExpanded
and useGroupBy
to compute expanded states for individual rows.subRows: Array<Row>
state: Object
data
array. When the raw data
is changed, this state value is reset to the row's initial value (using the initialRowStateKey
option).instance.setRowState
or the row's setState
function.The following additional properties are available on every Cell
object returned in an array of cells
on every row object.
column: Column
row: Row
value: any
Cell
renderer. To override the way a cell displaysgetCellProps: Function(?props)
getCellProps
hook to extend its functionality.render: Function(type: String | Function | Component, ?props)
instance
will be passed to the renderer with the addition of column
, row
and cell
properties, containing a reference to each respective item.type
is a string, will render using the column[type]
renderer. React Table ships with a default Cell
renderer. Other renderers like Aggregated
are available via hooks like useFilters
.useSortBy
useSortBy
is the hook that implements row sorting. It also support multi-sort (keyboard required).
getSortByToggleProps()
, then click any of those elements.shift
while clicking on any of those same elements that have the props from getSortByToggleProps()
attached.toggleSortBy
method located on the instance or each individual column.The following options are supported via the main options object passed to useTable(options)
state[0].sortBy: Array<Object<id: columnID, desc: Bool>>
id
key with the corresponding column ID to sort by. An optional desc
key may be set to true or false to indicated ascending or descending sorting for that column. This information is stored in state since the table is allowed to manipulate the filter through user interaction.manualSorting: Bool
disableSorting: Bool
disableMultiSort: Bool
isMultiSortEvent: Function
event
as argument.maxMultiSortColCount: Number
[A, B, C]
and then clicking D
for sorting should result in table sorted by [B, C , D]
disableSortRemove: Bool
disableMultiRemove: Bool
orderByFn: Function
sortTypes: Object<sortKey: sortType>
The following options are supported on any Column
object passed to the columns
options in useTable()
disableSorting: Bool
false
true
, the sorting for this column will be disabledsortDescFirst: Bool
false
true
, the first sort direction for this column will be descending instead of ascendingsortInverted: Bool
false
true
, the underlying sorting direction will be inverted, but the UI will not.sortType: String | Function
basic
, datetime
, alphanumeric
. Defaults to alphanumeric
.string
is passed, the function with that name located on either the custom sortTypes
option or the built-in sorting types object will be used.function
is passed, it will be used.The following values are provided to the table instance
:
rows: Array<Row>
preSortedRows: Array<Row>
toggleSortBy: Function(ColumnID: String, descending: Bool, isMulti: Bool) => void
The following properties are available on every Column
object returned by the table instance.
canSort: Bool
toggleSortBy: Function(descending, multi) => void
instance
-level toggleSortBy
, however, passing a columnID is not required since it is located on a Column
object already.getSortByToggleProps: Function(props) => props
getSortByToggleProps
hook to extend its functionality.clearSorting: Function() => void
isSorted: Boolean
sortedIndex: Int
sortBy
array from state that corresponds to this column.-1
isSortedDesc: Bool
true
, the column is sorted descending
false
, the column is sorted ascending
undefined
, the column is not currently being sorted.useFilters
useFilters
is the hook that implements row filtering.
The following options are supported via the main options object passed to useTable(options)
state[0].filters: Object<columnID: filterValue>
defaultFilter: String | Function
text
string
is passed, the function with that name located on the filterTypes
option object will be used.function
is passed, it will be used.manualFilters: Bool
disableFilters: Bool
filterTypes: Object<filterKey: filterType>
The following options are supported on any Column
object passed to the columns
options in useTable()
Filter: Function | React.Component => JSX
disableFilters: Bool
true
, will disable filtering for this columnfilter: String | Function
text
string
is passed, the function with that name located on either the custom filterTypes
option or the built-in filtering types object will be used. Iffunction
is passed, it will be used directly.The following values are provided to the table instance
:
rows: Array<Row>
preFilteredRows: Array<Row>
rows
do not contain every possible option.setFilter: Function(columnID, filterValue) => void
setAllFilters: Function(filtersObject) => void
The following properties are available on every Column
object returned by the table instance.
canFilter: Bool
setFilter: Function(filterValue) => void
filterValue: any
filters
objectpreFilteredColumnRows: Array<row>
useGroupBy
useGroupBy
is the hook that implements row grouping and aggregation.
getGroupByToggleProps()
function can be used to generate the props needed to make a clickable UI element that will toggle the grouping on or off for a specific column.toggleGroupBy
functions are also made available for programmatic grouping.The following options are supported via the main options object passed to useTable(options)
state[0].groupBy: Array<String>
manualGroupBy: Bool
disableGrouping: Bool
aggregations: Object<aggregationKey: aggregationFn>
groupByFn: Function
defaultGroupByFn
state.groupBy
keys provided. It's very rare you would need to customize this function.The following options are supported on any Column
object passed to the columns
options in useTable()
Aggregated: Function | React.Component => JSX
Cell
formatterAggregated
function for this column could format that value to 1,000 Avg. Visits
disableGrouping: Boolean
true
true
, this column is able to be grouped.The following values are provided to the table instance
:
rows: Array<Row>
preGroupedRows: Array<Row>
toggleGroupBy: Function(columnID: String, ?set: Bool) => void
The following properties are available on every Column
object returned by the table instance.
canGroupBy: Boolean
true
, this column is able to be grouped.useGroupBy
related optionsisGrouped: Boolean
true
, this column is currently being groupedgroupedIndex: Int
groupBy
array.toggleGroupBy: Function(?set: Bool) => void
getGroupByToggleProps: Function(props) => props
getGroupByToggleProps
hook to extend its functionality.The following properties are available on every Row
object returned by the table instance.
groupByID: String
undefined
if the row is an original row from data
and not a materialized one from the grouping.groupByVal: any
values: Object
values
objectsubRows: Array<Row>
depth: Int
path: Array<String|Int>
Row
objects, materialized grouping rows also have a path array. The keys inside it though are not integers like nested normal rows though. Since they are not rows that can be traced back to an original data row, they are given a unique path based on their groupByVal
['Single']
or ['Complicated', 'Anderson']
, where Single
, Complicated
, and Anderson
would all be derived from their row's groupByVal
.isAggregated: Bool
true
if the row is an aggregated rowThe following additional properties are available on every Cell
object returned in an array of cells
on every row object.
isGrouped: Bool
true
, this cell is a grouped cell, meaning it contains a grouping value and should usually display and expander.isRepeatedValue: Bool
true
, this cell is a repeated value cell, meaning it contains a value that is already being displayed elsewhere (usually by a parent row's cell).isAggregated: Bool
true
, this cell's value has been aggregated and should probably be rendered with the Aggregated
cell renderer.useExpanded
useExpanded
is the hook that implements row expanding. It is most often used with useGroupBy
to expand grouped rows or on its own with nested subRows
in tree-like data
sets, but is not limited to these use-cases. It supports expanding rows both via internal table state and also via a hard-coded key on the raw row model.
The following options are supported via the main options object passed to useTable(options)
state[0].expanded: Array<pathKey: String>
row.path.join('.')
) is present in this array, that row will have an expanded state. For example, if ['3']
was passed as the expanded
state, the 4th row in the original data array would be expanded..
to expand sub rows. For example, if ['3', '3.5']
was passed as the expanded
state, then the 6th subRow of the 4th row and also the 4th row of the original data array would be expanded.getSubRows: Function(row, relativeIndex) => Rows[]
manualExpandedKey: String
expanded
{ name: 'Tanner Linsley', friends: [...], expanded: true}
was detected, it would always be expanded, regardless of state.expandSubRows: Bool
true
true
, expanded rows are rendered along with normal rows.false
, expanded rows will only be available through their parent row. This could be useful if you are implementing a custom expanded row view.The following properties are available on the table instance returned from useTable
rows: Array<Row>
The following additional properties are available on every row
object returned by the table instance.
isExpanded: Bool
true
, this row is in an expanded state.toggleExpanded: Function(?isExpanded: Bool) => void
true
and false
or, if an isExpanded
boolean is passed to the function, it will be set as the new isExpanded
value.manualExpandedKey
(defaults to expanded
) set to true
are not affected by this function or the internal expanded state.usePagination
usePagination
is the hook that implements row pagination. It can be used for both client-side pagination or server-side pagination. For more information on pagination, see Pagination
NOTE Some server-side pagination implementations do not use page index and instead use token based pagination! If that's the case, please use the
useTokenPagination
plugin instead.
The following options are supported via the main options object passed to useTable(options)
state[0].pageSize: Int
10
state[0].pageIndex: Int
0
page
instance valuepageCount: Int
manualPagination
is set to true
manualPagination
is true
, then this value used to determine the amount of pages available. This amount is then used to materialize the pageOptions
and also compute the canNextPage
values on the table instance.manualPagination: Bool
disablePageResetOnDataChange
false
rows
, state.filters
, state.groupBy
, or state.sortBy
will trigger the pageIndex
to be reset to 0
true
, the pageIndex
will not be automatically set to 0
when these dependencies change.paginateExpandedRows: Bool
useExpanded
plugin hook simultaneouslytrue
true
, expanded rows are paginated along with normal rows. This results in stable page sizes across every page.false
, expanded rows will be spliced in after pagination. This means that the total number of rows in a page can potentially be larger than the page size, depending on how many subrows are expanded.The following values are provided to the table instance
:
page: Array<row>
pageIndex
value.pageCount: Int
manualPagination
is set to false
, this is the total amount of pages available in the table based on the current pageSize
valuemanualPagination
is set to true
, this is merely the same pageCount
option that was passed in the table options.pageOptions: Array<Int>
canPreviousPage: Bool
pageIndex
is greater than 0
, this will be true
canNextPage:
pageIndex
is less than pageCount
, this will be true
gotoPage: Function(pageIndex)
pageIndex
, will set pageIndex
to that value.pageIndex
range, then this function will do nothing.previousPage: Function
state.pageIndex
by one.canPreviousPage
is false, this function will do nothing.nextPage: Function
state.pageIndex
by one.canNextPage
is false, this function will do nothing.setPageSize: Function(pageSize)
state.pageSize
to the new value.state.pageIndex
is also calculated. It is calculated via Math.floor(currentTopRowIndex / newPageSize)
pageIndex: Int
state.pageIndex
value.pageSize: Int
state.pageSize
value.useTokenPagination (Coming Soon)
useTokenPagination
is the hook that aids in implementing row pagination using tokens. It is useful for server-side pagination implementations that use tokens instead of page index. For more information on pagination, see Pagination
Documentation Coming Soon...
useRowSelect
useRowSelect
is the hook that implements basic row selection. For more information on row selection, see Row Selection
The following options are supported via the main options object passed to useTable(options)
state[0].selectedRows: Array<RowPathKey>
[]
[1, 3, 2]
would have a path key of 1.3.2
) is found in this array, it will have a selected state.manualRowSelectedKey: String
isSelected
The following values are provided to the table instance
:
toggleRowSelected: Function(rowPath: String, ?set: Bool) => void
true
or false
to set it to that statetoggleRowSelectedAll: Function(?set: Bool) => void
true
or false
to set all rows to that stategetToggleAllRowsSelectedProps: Function(props) => props
onChange: Function()
style.cursor: 'pointer'
checked: Bool
title: 'Toggle All Rows Selected'
isAllRowsSelected: Bool
true
if all rows are selected.false
The following additional properties are available on every prepared row
object returned by the table instance.
isSelected: Bool
true
if the row is currently selectedtoggleRowSelected: Function(?set)
true
or false
to set it to that stateuseRowState
useRowState
is a plugin hook that implements basic state management for prepared rows and their cells.
The following options are supported via the main options object passed to useTable(options)
state[0].rowState: Object<RowPathKey:Object<any, cellState: {columnID: Object}>>
{}
[1, 3, 2]
would have a path key of 1.3.2
) is found in this array, it will have the state of the value corresponding to that key.cellState
key, which provides cell-level state based on column ID's to every
prepared cell in the table.initialRowStateAccessor: Function
Row
object, from which you can return a value to use as the initial state, eg. row => row.original.initialState
The following values are provided to the table instance
:
setRowState: Function(rowPath: Array<string>, updater: Function | Any) => void
updater
can be a function or value. If a function
is passed, it will receive the current value and expect a new one to be returned.setCellState: Function(rowPath: Array<string>, columnID: String, updater: Function | Any) => void
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.The following additional properties are available on every prepared row
object returned by the table instance.
state: Object
rowState
object via rowState[row.path.join('.')]
cellState
key/value pair, which is used to provide individual cell states to this row's cellssetState: Function(updater: Function | any)
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.The following additional properties are available on every Cell
object returned in an array of cells
on every row object.
state: Object
rowState
object via rowState[row.path.join('.')].cellState[columnID]
setState: Function(updater: Function | any)
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
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 for more information on these options.
getRowProps
getCellProps
getHeaderProps
useAbsoluteLayout
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 for more information on these options.
getTableBodyProps
getRowProps
getCellProps
getHeaderProps
useColumnOrder
useColumnOrder
is a plugin hook that implements basic column reordering. As columns are reordered, their header groups are reverse-engineered so as to never have orphaned header groups.
The following options are supported via the main options object passed to useTable(options)
state[0].columnOrder: Array<ColumnID>
[]
column
structureThe following values are provided to the table instance
:
setColumnOrder: Function(updater: Function | Array<ColumnID>) => void
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.useTableState
useTableState
is a hook that allows you to hoist the table state out of the table into your own code. You should use this hook if you need to:
Some common use cases for this hook are:
pageIndex
and pageSize
changes for server-side pagination to fetch new dataThe following options are supported via the main options object passed to useTable(options)
initialState: Object
defaultState
object (eg. {...defaultState, ...initialState}
) that React Table and its hooks use to register default state to produce the final initial state object passed to the resolved useState
hook.overrides: Object
{...state, ...overrides}
) to produce the final state object that is then passed to the useTable
optionsoptions: Object
reducer: Function(oldState, newState) => finalState
setState
call to a table state (even internally), this reducer is called and is allowed to modify the final state object for updating.oldState
, the newState
, and an optional action type
.useState
React.useState
React.useState
. This can be useful for implementing custom state storage hooks like useLocalStorage, etc.tableStateTuple: [tableState, setTableState]
React.useState
useTableState
options change.tableState: Object
initialState
, overrides
and the reducer
options (if applicable)setTableState: Function(updater, type) => void
reducer
is changedupdater: Function
React.setState
. It is passed the previous state and is expected to return a new version of the state.updater
must be a function. Passing a replacement object is not supported as it is with React.useStatetype: String
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。