How can I make a summary row like this using a material table? Please help me, thank you.
Asked
Active
Viewed 3,826 times
2 Answers
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
