Building Reusable Table Component with Custom Hooks
Shows how to abstract the sorting and filtering logic of React TanStack Table into custom hooks for building a reusable table component, demonstrating how to encapsulate functionality and simplify the main component structure.
import { useTable, useSortBy, useFilters } from 'react-table';
function useCustomTable({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
},
useFilters,
useSortBy
);
return { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow };
}
This code defines a custom hook called useCustomTable that encapsulates the logic for initializing and setting up a table with sorting and filtering functionality using the react-table library. The hook takes an object with columns and data as parameters, then calls useTable hook along with useFilters and useSortBy to add filtering and sorting capabilities. It returns the necessary properties and functions for rendering the table.
function Table({ columns, data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useCustomTable({ columns, data });
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps(column.getSortByToggleProps())}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
}
This code snippet demonstrates how to use the custom hook 'useCustomTable' within a Table component. It destructures the return values from the hook (getTableProps, getTableBodyProps, headerGroups, rows, prepareRow) to set up and render a table. The component iterates over header groups to render table headers with sorting actions and over rows to display the table data. Sorting is enabled by clicking on the headers, utilizing the getSortByToggleProps method provided by react-table.