React-Table: initialState

Contents

initialState

In our useTable post we talked about how we used our parent component <PeopleDataTable> just as a means to pass data, columns and settings to the <DataTable> component. Well this is where settings come in.

We’ve learned how to add filters and sorting. Now we want to set a default filter on a specific column, and a default sort on another column, at the same time, when the table loads.

We accomplish this with the initialState prop.

Edit throbbing-river-vs4shw

We start by creating a new object in the parent component with the settings for this particular table. We want to filter for only single people and sort the last names in descending order.

Then we pass this new object as a prop.

/components/PeopleDataTable.js
import React, { Component } from "react";

// components
import Datatable from "./DataTable";
import Loading from "./Loading";

// utilities
import makeData from "../utilities/makeData";

// filters
import { DropdownFilter, TextSearchFilter } from "../utilities/filters";

const data = makeData(20);

const columns = [
  {
    Header: "First Name",
    accessor: "firstName",
    Filter: TextSearchFilter,
    filter: "rankedMatchSorter"
  },
  // ...
];

const initialState = {
  sortBy: [
    {
      id: "lastName",
      desc: false
    }
  ],
  filters: [
    {
      id: "status",
      value: "single"
    }
  ]
};

class PeopleDataTable extends Component {
  // Loading must be handled here because DataTable MUST have data on load
  renderTable() {
    if (!data) {
      return <Loading />;
    } else {
      return (
        <Datatable data={data} columns={columns} initialState={initialState} />
      );
    }
  }

  render() {
    return <>{this.renderTable()}</>;
  }
}

export default PeopleDataTable;

and then in the DataTable component we memoize props.initialState and pass it to the useTable hook.

/components/DataTable.js
import React from "react";
import { useTable, useFilters, useSortBy } from "react-table";

// utilities
import { matchSorterFn } from "../utilities/sorting";

const DataTable = (props) => {
  // MEMOS
  const data = React.useMemo(() => props.data, [props.data]);
  const columns = React.useMemo(() => props.columns, [props.columns]);
  const initialState = React.useMemo(() => props.initialState);
  const defaultColumn = React.useMemo(
    () => ({
      // Let's set up our default Filter UI
      Filter: ""
    }),
    []
  );
  const filterTypes = React.useMemo(
    () => ({
      rankedMatchSorter: matchSorterFn
    }),
    []
  );

  // CONFIGURE useTable
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable(
    {
      columns,
      data,
      defaultColumn,
      filterTypes,
      initialState
    },
    useFilters,
    useSortBy
  );

  // RENDERING
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>
                <div>
                  {column.render("Header")}
                  <span>
                    {column.isSorted
                      ? column.isSortedDesc
                        ? " 🔽"
                        : " 🔼"
                      : ""}
                  </span>
                </div>
                <div>{column.canFilter ? column.render("Filter") : null}</div>
              </th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default DataTable;

That is it. That’s all it takes. There are lots of other initialState settings you can add, and information on those is available in the documentation. You will come across them as you go.