Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 Β· Projects and Practice

Project: Data Table with Filters

Build a data table with Material UI: debounced search, status filter chips, sorting, pagination, empty and loading states, and URL-friendly state, with a runnable stand-in.

The third project combines the table, input and feedback lessons into the screen that business users live in: a list of records with search, filters, sorting and pagination, plus the states people forget: loading, empty and error. You will see how to structure the code so that the filtering logic is separate from the UI, and how to keep the table's state in the URL so that a link reproduces the same view.

Material UI cannot run in the live editors here. The code samples are real MUI, read-only. The runnable preview is a stand-in with the same state model and behavior, written with plain React and CSS.

Design the state

Everything the user can change is a query. Keep it as one object, and derive the visible rows from the data and the query with a pure function:

TSX
// Real TypeScript, read-only: src/tableQuery.ts
export type Query = {
  search: string;
  status: 'all' | 'Active' | 'Invited' | 'Suspended';
  sort: 'name' | 'role' | 'joined';
  order: 'asc' | 'desc';
  page: number;      // zero-based
  pageSize: number;
};

export function applyQuery(rows: Member[], q: Query) {
  const needle = q.search.trim().toLowerCase();
  const filtered = rows.filter((r) =>
    (q.status === 'all' || r.status === q.status) &&
    (needle === '' || r.name.toLowerCase().includes(needle) || r.email.toLowerCase().includes(needle)),
  );
  const sorted = [...filtered].sort((a, b) => {
    const result = String(a[q.sort]).localeCompare(String(b[q.sort]));
    return q.order === 'asc' ? result : -result;
  });
  const start = q.page * q.pageSize;
  return { total: filtered.length, rows: sorted.slice(start, start + q.pageSize) };
}

Two rules make it work: any change to search, filter or page size resets page to 0, and the function returns total (the filtered count) for the pagination component. Because applyQuery is pure it is trivial to unit test, and later you can replace it with a server request that takes the same Query.

Controls

TSX
// Real Material UI, read-only: the toolbar above the table
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ mb: 2 }} alignItems={{ sm: 'center' }}>
  <TextField
    size="small"
    label="Search members"
    type="search"
    value={searchInput}
    onChange={(e) => setSearchInput(e.target.value)}
    slotProps={{
      input: {
        startAdornment: (
          <InputAdornment position="start"><SearchIcon fontSize="small" /></InputAdornment>
        ),
      },
    }}
    sx={{ minWidth: 260 }}
  />

  <Stack direction="row" spacing={1} role="group" aria-label="Filter by status">
    {['all', 'Active', 'Invited', 'Suspended'].map((s) => (
      <Chip
        key={s}
        label={s === 'all' ? 'All' : s}
        color={query.status === s ? 'primary' : 'default'}
        variant={query.status === s ? 'filled' : 'outlined'}
        onClick={() => update({ status: s })}
        aria-pressed={query.status === s}
      />
    ))}
  </Stack>
</Stack>

The search box keeps its own searchInput state, updating the query after a short debounce (250 to 300 ms), so typing stays smooth and a server is not hit on every keystroke. A Chip with onClick is a button and receives focus and keyboard activation; aria-pressed tells assistive technology which filter is on.

The table states

A good data view always handles four states:

State What to show
Loading Skeleton rows with the table's real column widths, or a LinearProgress above the table
Data The table and pagination
Empty A message that explains why and offers an action ("No members match 'zed'. Clear filters")
Error An Alert with a Retry button; the previous data may stay visible

Announce changes: put the result count in an element with aria-live="polite" (for example "12 members") so screen readers hear the effect of a filter.

State in the URL

When the query lives in the URL (?q=ada&status=Active&page=2), the browser's back button, bookmarks and shared links all work. With a router: read the useSearchParams() value to build the Query, and write changes with setSearchParams. Use replace for typing in the search box so you do not fill the history with a new entry for every debounce tick.

TSX
// Real React Router, read-only
const [params, setParams] = useSearchParams();
const query: Query = {
  search: params.get('q') ?? '',
  status: (params.get('status') as Query['status']) ?? 'all',
  sort: (params.get('sort') as Query['sort']) ?? 'name',
  order: params.get('order') === 'desc' ? 'desc' : 'asc',
  page: Number(params.get('page') ?? 0),
  pageSize: Number(params.get('size') ?? 10),
};

Validate what you read: users can type anything into a URL, so check that sort is one of your columns and page is a non-negative integer before using it. See the React Router tutorial for search params in depth.

Try it: the filterable table

This stand-in uses the same applyQuery approach. It has a debounced search, status chips, sortable columns, pagination, an empty state with a "Clear filters" action and a result count announced politely. The data load is simulated with a short delay so you can see the loading skeleton; press Reload to see it again.

Members table: search, filter, sort, paginate

Try it: debounce on its own

Debouncing is easy to get wrong, so look at it in isolation. Type quickly: the "requests" counter only increases when you pause.

Debounce: fewer requests while typing

Server-side tables

When the data does not fit in the browser, send the Query to the server and render what comes back (rows and total). Changes:

  • The toolbar and table stay the same; applyQuery becomes fetchMembers(query).
  • Use a library for server state (TanStack Query or SWR) so that you get caching, keepPreviousData (the old rows stay visible while the new page loads), cancellation of stale requests and retries.
  • With the MUI X Data Grid, set paginationMode="server", sortingMode="server" and filterMode="server" and handle the model change callbacks.
  • Debounce search, cancel outdated requests with AbortController and ignore out-of-order responses.

Improve it

  1. Sync the query with the URL and verify the back button restores the previous filters.
  2. Add a column visibility menu using Menu and Checkbox.
  3. Add row selection with a bulk action bar ("Suspend 3 members") using the pattern from Tables, Pagination and Data Grid.
  4. Replace the stand-in table with a Data Grid and compare the code size.
  5. Export the filtered rows to CSV, and announce the result with a Snackbar.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why reset page to 0 whenever the search, filter or page size changes?

    After filtering there may be fewer pages. Staying on page 5 of 2 would show nothing.
  2. 2. What does debouncing a search box achieve?

    Each keystroke restarts a timer, so only the final value after a pause triggers the search.
  3. 3. What is a benefit of putting table state in the URL?

    The URL then represents the view, so navigation and sharing just work.
  4. 4. Which states must a data view handle besides showing data?

    Users meet all three. Skeletons for loading, a helpful message with an action for empty, and an Alert with Retry for errors.

Summary

  • Model the view as a Query object and derive rows with a pure function that returns the rows and the total.
  • Debounce search, reset the page on every other change and announce the count with aria-live.
  • Handle loading (skeleton), empty (with an action) and error (Alert with retry).
  • Keep the query in the URL, validating what you read, and move to server-side queries and a server-state library when the data is large.

Next: Practice Exercises and Cheat Sheet