Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 847
Srikanth Gowda Avatar asked Sep 07 '18 07:09

Srikanth Gowda


1 Answers

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.

like image 169
prathap K Avatar answered Oct 19 '22 05:10

prathap K