3

summary row

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

Mushroomator
  • 6,516
  • 1
  • 10
  • 27
Jargalan
  • 81
  • 2
  • 3

2 Answers2

0

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).

kbo
  • 422
  • 5
  • 17
  • what about sorting ? doesn't it break ? – johnnyBoy Feb 09 '23 at 15:55
  • @johnnyBoy depends how it's done. If you only sort `data` and only after that call `addTotal`, should be good. It don't think it's a good idea to keep the summation/totals row in the same data set (same array) as other values. – kbo Feb 10 '23 at 16:07
0

I might be a little late, but here’s another question that reminded me that material table happen to have a footer row api.

You can use it alongside a specific method to sum values (or else) that you can call before setting the datasource for example, or on demand.

johnnyBoy
  • 115
  • 2
  • 12