Search code examples
cssreactjsmaterial-table

Fix the last row of react material-table to display the sum of a particular column?


We have a requirement display the total sum for 2 columns

Material Table

import MaterialTable, {MTableToolbar, MTableAction} from "material-table";
.
.
.
<MaterialTable
            actions={transformActions()}
            data={data}
            editable={props.allowRowEditing ? {
                onRowAdd: newData => onRowAdd(newData),
                onRowDelete: oldData => onRowDelete(oldData),
                onRowUpdate: (newData, oldData) => onRowUpdate(newData, oldData)
            } : {}}
            icons={tableIcons}
.
.
./>

I have a function to calculate the total and display the total; however on sorting the column, the row that displays the total moves around as well. Is there a way to fix the last row in material-table itself? Or are there any style hacks that can be done to achieve this?

Based on below issue report, there isn't any way as of now to achieve this using material table's properties

Github Issue#27

Note that I am not at liberty to use another table library.

I have tried to target the last row and set it's position as absolute as shown below

    position: absolute;
    height: 55px;
    width: calc(100% - 1px);
    bottom: 0;

while this fixes the last row in its position, I can't find a dynamic way to align the columns in accordance to the other rows.

Material table after css changes


Solution

  • You can use the TableFooter element to stick your totals to the bottom of the table.

    An example of overriding the body component to add a footer:

    import { TableCell, TableFooter, TableRow } from "@material-ui/core";
    // ...
    
        <MaterialTable
            // ...
            components={{
              Body: (props) => (
                <>
                  <MTableBody {...props}/>
                  <TableFooter>
                    <TableRow>
                      <TableCell colSpan={2}/>
                      <TableCell colSpan={2}>Total: 12345</TableCell>
                    </TableRow>
                  </TableFooter>
                </>
              )
            }}
        />
    

    Working example here: https://codesandbox.io/s/long-tree-fqkno