'material-table: How to make a summary row?

summary row

How can I make a summary row like this using a material table? Please help me, thank you.



Solution 1:[1]

If by "Summary row" you're referring to table title, that's a prop "title" you just add to the <MaterialTable /> component.

However, I suspect you need the row with Total result, which I couldn't find in the examples, either. Here's a custom function you could use to calculate a total by your own, add it to your data set and achieve similar result:

const addTotal = (data, byColumn) => {
  let keys = Object.keys(data[0]);
  let total = data.reduce((acc, el) => {
    return acc += +(el[byColumn]);
  }, 0);

  let totalRow = {};
  let emptyRow = {};
  for (let key of keys) {
    if (key === keys[0]) {
      totalRow[key] = 'Total';
    } else if (key === byColumn) {
      totalRow[key] = total;
    } else {
      totalRow[key] = '';
    }
    emptyRow[key] = '';
  }
  return [...data, emptyRow, totalRow];
}

This will add an empty row and a total with the argument you put as byColumn. You need to be careful about the values you are summing (i.e. add type checking or validate the column name with hasOwnProperty).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1