Summary Row React Table (with Lodash)

Summary Row React Table (with Lodash)

If you're familiar with React and Lodash, and you're building a table with summary rows, you might find this useful.

What is a summary row?

A summary row is a row at the bottom of a table that displays aggregate information about the data in the table. For example, it could display the total sales revenue for all the rows in the table.

How do you create a summary row with React and Lodash?

First, you'll need to install Lodash:

npm install lodash

Then, you'll need to create a function that calculates the summary data. Here's an example:

import _ from 'lodash';

function calculateSummaryData(data) {
  const totalSales = _.sumBy(data, 'sales');
  return { totalSales };

This function takes an array of data as its input, and uses Lodash's sumBy method to calculate the total sales. It returns an object with the summary data.

Next, you'll need to modify your table component to include the summary row. Here's an example:

import React from 'react';

function Table({ data }) {
  const summaryData = calculateSummaryData(data);

  return (
        {, index) => (
          <tr key={index}>

In this example, we've added a <tfoot> element to the table, which contains the summary row. We're using the summaryData object that we calculated earlier to display the total sales.

And that's it! You now have a table with a summary row.

Other ways to create a summary row

There are many ways to create a summary row in React, and not all of them require Lodash. Here are a few other options:

  • Use the reduce method to calculate the summary data. This is similar to using Lodash's sumBy, but you'll need to write your own function to calculate the summary data.
  • Pass the summary data as a prop to the table component. This can be useful if you're calculating the summary data in a parent component.
  • Create a separate component for the summary row. This can make your code more modular and reusable.

Experiment with these options and see which one works best for your use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]