Mind you above answer from user Linschlager might not work if you're using react-table's sorting hook useSortBy
. Indeed, the authors final solution did not involve react.useMemo
.
To me it worked out anyways. My columns- and row-data came from a query-data object that I had to resolve to fit the specific way react-table does it.
It looked something like this:
function ReportTable({ queryData }) {
... other data such as {selectedPerLevel} ...
/* COLUMNS */
let firstColumn = {
Header: ' ',
columns: [
{
Header: selectedPerLevel.name,
accessor: 'perLevel',
},
],
};
let otherColumns = [];
queryData.weeks.forEach((week) => {
let otherColumn = {
Header: week,
Footer: ' ',
center: true,
columns: [
{
Header: 'Ratio',
accessor: `ratio${week}`,
},
{
Header: 'Count',
accessor: 'count' + week,
},
],
};
otherColumns = [...otherColumns, otherColumn];
});
/* ROWS */
let listOfRows = queryData.units.map((unit) => {
let row = {};
// for each column
unit.items.forEach(({ week, ratio, count}) => {
row = {
...row,
['ratio' + week]: ratio,
['count' + week]: count,
};
});
// add the first column-data to the row
row = { ...row, perLevel: unit.name, id: unit.id };
return row;
});
const data = React.useMemo(() => listOfRows, [queryData]);
const columns = React.useMemo(() => [{ ...firstColumn }, ...otherColumns], [queryData]);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({data, columns}, useSortBy);
return <Table ....
I don't know if this is to anyones help but it all worked out fine for me with above solution.