Implementing Basic Row Grouping
Demonstrate how to group rows based on a specific property in React TanStack Table, including the initial setup and configuration for row grouping.
import { useTable, useGroupBy } from '@tanstack/react-table';Import necessary hooks from TanStack Table.
import React from 'react';Import React to use in your component.
// Define your Table componentComment line for organizing code.
const TableComponent = ({ columns, data }) => {Initialize the TableComponent with columns and data props.
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data }, useGroupBy);Initialize useTable hook with grouping functionality.
return (Start of the return statement for JSX rendering.
<table {...getTableProps()}>Create a table and spread table props.
<thead>Define the table header group.
{headerGroups.map(headerGroup => (Map each header group for rendering.
<tr {...headerGroup.getHeaderGroupProps()}>Create a table row for each header group and spread header group props.
{headerGroup.headers.map(column => (Map each header in the header group for rendering.
<th {...column.getHeaderProps()}>{column.render('Header')}</th>Create a table header for each column and render the Header property.
))}End of mapping headers.
</tr>Close the table row tag for the header group.
))}End of mapping header groups.
</thead>Close the table header tag.
<tbody {...getTableBodyProps()}>Create the table body and spread table body props.
{rows.map(row => {Map each row for rendering.
prepareRow(row);Call prepareRow method with the current row.
return (Return statement for each row render.
<tr {...row.getRowProps()}>Create a table row for each row and spread row props.
{row.cells.map(cell => {Map each cell in the row for rendering.
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;Create a table data for each cell and render the Cell property.
})}End of mapping cells.
</tr>Close the table row tag for the current row.
);Close return statement for row render.
})}End of mapping rows.
</tbody>Close the table body tag.
</table>Close the table tag.
);Close the return statement for JSX.
};Close the TableComponent function.
export default TableComponent;Export the TableComponent for use in other parts of your app.