6

React tables Calculating Footer sum on page change on Sort on search, how can we achieve that.

import React from "react";
import { render } from "react-dom";
import ReactTable from "react-table";
import "react-table/react-table.css";

const data = [
  {
    id: 1,
    product: "apple",
    stock: 1,
    price: 123
  },
  {
    id: 2,
    product: "pie",
    stock: 2,
    price: 22
  }
];

const App = () => (
  <div>
    <ReactTable 
      data={data}
      columns={[
        {
          Header: "Id",
          accessor: "id"
        },
        {
          Header: "Product",
          accessor: "product",
          Footer: "Summary"
        },
        {
          Header: "Stock",
          accessor: "stock"
        },
        {
          Header: "Price",
          accessor: "price",
          Footer: (
            <span>{
              data.reduce((total, { price }) => total += price, 0)
            }</span>
          )
        }
      ]}
      defaultPageSize={2}
    />
  </div>
);

above code can be used to get the sum of a column data of all the rows, can anyone please guide me in a right way.

Srikanth Gowda
  • 6,163
  • 7
  • 19
  • 34

1 Answers1

2

Import this first:

import _ from "lodash";

Then below code should resolve your issue:

{
  Header: "Price",
  accessor: "price",
  id: "price"
  Footer: <span>{_.sum(_.map(data, d => d.price))}</span>
  )
}

Please note that there should be underscore symbol between { and .sum.
Similarly underscore symbol between ( and .map
Somehow it is removed when I posted my code here.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
prathap K
  • 91
  • 1
  • 1
  • 10