r121
r121

Reputation: 2738

How to get length of the current data in react table

I want to know how to get the current length of the data in react table. I am getting a current count of all the data using this code const count = preGlobalFilteredRows.length; but after filtering data using globalFilter and I want to know how to get the updated length of the array to show on the title of the page using react-helmet.

Table code:

import React, { useState } from "react";
import {
  useTable,
  useGlobalFilter,
  useAsyncDebounce,
  useSortBy,
  usePagination,
} from "react-table";
import Button, { PageButton } from "../reusable/Button";
import CsvDownload from "react-json-to-csv";
import exportToJson from "../../utils/exportFile";
import { Helmet } from "react-helmet";

const GlobalFilter = ({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter,
}) => {
  const count = preGlobalFilteredRows.length;
  console.log(count);
  const [value, setValue] = useState(globalFilter);
  const onChange = useAsyncDebounce((value) => {
    setGlobalFilter(value || undefined);
  }, 200);

  return (
    <>
      <Helmet>
        <title>{`${count} Records found`}</title>
      </Helmet>
      <label className="flex gap-x-2 items-baseline">
        <span className="text-primary-dark">Search: </span>
        <input
          type="text"
          className="text-primary-dark rounded-md border-gray-300 shadow-sm outline-none p-2"
          value={value || ""}
          onChange={(e) => {
            setValue(e.target.value);
            onChange(e.target.value);
          }}
          placeholder={`${count} records...`}
        />
      </label>
    </>
  );
};

const Table = ({ columns, data, completeData, query }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    page,
    prepareRow,
    previousPage,
    nextPage,
    canPreviousPage,
    canNextPage,
    state,
    setPageSize,
    pageOptions,
    gotoPage,
    pageCount,
    setGlobalFilter,
    preGlobalFilteredRows,
  } = useTable(
    {
      columns,
      data,
    },
    useGlobalFilter,
    useSortBy,
    usePagination
  );
  return (
    <>
      <div className="flex justify-between items-center">
        <GlobalFilter
          preGlobalFilteredRows={preGlobalFilteredRows}
          globalFilter={state.globalFilter}
          setGlobalFilter={setGlobalFilter}
        />
        <div>
          <CsvDownload
            className="bg-primary-dark hover:bg-secondary-dark transition-colors text-white rounded-md font-semibold px-4 py-2 mr-3"
            data={completeData}
            filename={`${query}.csv`}
          >
            <i className="fas fa-arrow-down mr-2"></i> Download CSV
          </CsvDownload>
          <Button
            handleClick={() => exportToJson(completeData, query)}
            iconName="fas fa-arrow-down"
            btnName="Download JSON"
          />
        </div>
      </div>

      {/* table */}
      <div className="shadow overflow-auto border-b border-gray-200 sm:rounded-lg">
        <table
          {...getTableProps()}
          className="min-w-full divide-y divide-gray-200"
        >
          <thead className="bg-gray-50">
            {headerGroups.map((headerGroup) => (
              <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => (
                  <th
                    scope="col"
                    className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                    {...column.getHeaderProps(column.getSortByToggleProps())}
                  >
                    {column.render("Header")}
                    <span>
                      {column.isSorted
                        ? column.isSortedDesc
                          ? " ▼"
                          : " ▲"
                        : ""}
                    </span>
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody
            {...getTableBodyProps()}
            className="bg-white text-black divide-y divide-gray-200"
          >
            {page.map((row, i) => {
              prepareRow(row);
              return (
                <tr {...row.getRowProps()}>
                  {row.cells.map((cell) => {
                    return (
                      <td
                        {...cell.getCellProps()}
                        className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"
                      >
                        {cell.render("Cell")}
                      </td>
                    );
                  })}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      {/* Pagination */}
      <div className="py-3 flex items-center justify-between">
        <div className="flex-1 flex justify-between sm:hidden">
          <Button
            handleClick={() => previousPage()}
            disabled={!canPreviousPage}
            btnName="Previous"
          />
          <Button
            handleClick={() => nextPage()}
            disabled={!canNextPage}
            btnName="Next"
          />
        </div>
        <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div className="flex gap-x-2">
            <span className="text-sm text-gray-700">
              Page <span className="font-medium">{state.pageIndex + 1}</span> of{" "}
              <span className="font-medium">{pageOptions.length}</span>
            </span>
            <select
              className="text-black"
              value={state.pageSize}
              onChange={(e) => {
                setPageSize(Number(e.target.value));
              }}
            >
              {[5, 10, 20].map((pageSize) => (
                <option key={pageSize} value={pageSize}>
                  Show {pageSize}
                </option>
              ))}
            </select>
          </div>
          <div>
            <nav
              className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px"
              aria-label="Pagination"
            >
              <PageButton
                className="rounded-l-md"
                onClick={() => gotoPage(0)}
                disabled={!canPreviousPage}
              >
                <span className="sr-only">First</span>
                <i className="fas fa-angle-double-left"></i>
              </PageButton>
              <PageButton
                onClick={() => previousPage()}
                disabled={!canPreviousPage}
              >
                <span className="sr-only">Previous</span>
                <i className="fas fa-chevron-left"></i>
              </PageButton>
              <PageButton onClick={() => nextPage()} disabled={!canNextPage}>
                <span className="sr-only">Next</span>
                <i className="fas fa-chevron-right"></i>
              </PageButton>
              <PageButton
                className="rounded-r-md"
                onClick={() => gotoPage(pageCount - 1)}
                disabled={!canNextPage}
              >
                <span className="sr-only">Last</span>
                <i className="fas fa-angle-double-right"></i>
              </PageButton>
            </nav>
          </div>
        </div>
      </div>
    </>
  );
};

export default Table;

Upvotes: 1

Views: 8587

Answers (2)

Amos Machora
Amos Machora

Reputation: 585

in tanstack/react-table v8 this worked for me.

  const table = useReactTable();

  const { getRowModel } = table;

  const { rows } = getRowModel();
// then rows.length

Upvotes: 3

toki
toki

Reputation: 1005

From the useGlobalFilter docs:

rows: Array<Row>

An array of filtered rows.

If you want the number of filtered rows, just look at the length of the rows array from the useTable instance.

Upvotes: 3

Related Questions