Like you mentioned, using toggleAllRowsExpanded(true)
is going to be the easiest way to expand all of the rows. However, if you want this to happen within useTable
, you can write a custom plugin hook which runs this logic in the useInstance
hook based on a new initialState.startExpanded
boolean.
// useStartExpanded.tsx
import { useEffect } from 'react'
import { Hooks, TableInstance } from 'react-table'
export interface UseStartExpandedState<D extends object> {
startExpanded: boolean
}
export const useStartExpanded = <D extends object = {}>(hooks: Hooks<D>): void => {
hooks.useInstance.push(useInstance)
}
useStartExpanded.pluginName = 'useStartExpanded'
const useInstance = <D extends object = {}>(instance: TableInstance<D>): void => {
const {
state: { startExpanded },
toggleAllRowsExpanded
} = instance
useEffect(() => {
if (startExpanded) toggleAllRowsExpanded(true)
}, [startExpanded, toggleAllRowsExpanded])
}
Usage would look something like this:
// MyTable.tsx
import { useMemo } from 'react'
import { Column, useExpanded, useGroupBy, useTable } from 'react-table'
import { useStartExpanded } from './useStartExpanded'
export type Data = { id: string }
export const MyTable = ({ startExpanded = true }) => {
const data: Data[] = useMemo(() => [], [])
const columns: Column<Data>[] = useMemo(() => [], [])
const tableInstance = useTable<Data>(
{ columns, data, initialState: { startExpanded } },
useGroupBy,
useExpanded,
useStartExpanded
)
return <>...</>
}
Since this example is in TypeScript, you'll need to add the startExpanded
to the TableState
type definition.
// react-table-config.d.ts
import { UseExpandedState, UseGroupByState } from 'react-table'
import { UseStartExpandedState } from './useStartExpanded'
declare module 'react-table' {
export interface TableState<D extends object = {}>
extends UseExpandedState<D>,
UseGroupByState<D>,
UseStartExpandedState<D> {}
}