How to render row with totals for each grouping of rows? #6066
Replies: 1 comment
|
Yes, this is very common when building financial or operational tables. In TanStack Table, you can achieve this either by rendering a summary row after the group's sub-rows in the JSX, or by using the built-in column aggregation features. Here are the two standard patterns: Pattern 1: Render a Summary Row at the Bottom of Each Expanded Group (Recommended)When iterating through You can compute the group totals on-the-fly using <tbody>
{table.getRowModel().rows.map(row => {
// 1. Render the group header or leaf row
return (
<React.Fragment key={row.id}>
<tr>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
{/* 2. If this is a grouped row and it's expanded, render sub-rows + group total row */}
{row.getIsGrouped() && row.getIsExpanded() && (
<>
{row.subRows.map(subRow => (
<tr key={subRow.id} className="sub-row">
{subRow.getVisibleCells().map(cell => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
{/* 3. Group Total Summary Row at the bottom of the group */}
<tr className="bg-gray-100 font-semibold border-t">
{row.getVisibleCells().map(cell => {
const columnId = cell.column.id;
// For the grouped column, show a label
if (columnId === row.groupingColumnId) {
return (
<td key={cell.id}>
Total for {row.getValue(columnId)}
</td>
);
}
// For numeric columns, sum all leaf rows in this group
if (columnId === "amount" || columnId === "quantity") {
const groupTotal = row.getLeafRows().reduce((sum, leaf) => {
const val = leaf.getValue(columnId);
return sum + (typeof val === "number" ? val : 0);
}, 0);
return (
<td key={cell.id}>
{groupTotal.toLocaleString()}
</td>
);
}
return <td key={cell.id} />;
})}
</tr>
</>
)}
</React.Fragment>
);
})}
</tbody>Pattern 2: Built-in Column Aggregations with
|
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Is it possible to render a row for each grouping of rows, located at the bottom of each grouping and containing totals for some of the columns in those groupings?
All reactions