gridcn2.0.0
Sort, filter, and search

URL state

Sync sort, filter, search, column layout, and pagination to the URL with nuqs, so a reload or a shared link restores the view.

data-grid-url-state syncs the sort, filter, search, column layout, and page of the grid with the URL through nuqs. A reload or a shared link then restores the view. Install it, put a NuqsAdapter above the grid, and mount <DataGridUrlState> inside <DataGridProvider>.

pnpm dlx shadcn@latest add @gridcn/data-grid-url-state

Usage

Mount <DataGridUrlState> once inside <DataGridProvider>. It syncs only the sort and the group columns until you list filter and search in spec. The sample uses the toolbar add-on for the search box and the filter menu:

"use client";

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
  defineColumns,
} from "@/components/data-grid/data-grid";
import {
  DataGridFilterMenu,
  DataGridSearch,
  DataGridToolbar,
} from "@/components/data-grid-toolbar/data-grid-toolbar";
import {
  DataGridUrlState,
} from "@/components/data-grid-url-state/data-grid-url-state";

type Order = { id: string; customer: string; total: number };

const columns = defineColumns<Order>()([
  { id: "customer", header: "Customer", accessorKey: "customer" },
  { id: "total", header: "Total", accessorKey: "total", type: "number" },
]);

export function OrdersGrid({ rows }: { rows: Order[] }) {
  return (
    <DataGridProvider defaultData={rows} columns={columns}>
      <DataGridUrlState
        prefix="orders"
        spec={["sort", "filter", "search"]}
      />
      <DataGridToolbar>
        <DataGridSearch />
        <DataGridFilterMenu />
      </DataGridToolbar>
      <DataGridRoot className="h-96">
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
    </DataGridProvider>
  );
}

Render one NuqsAdapter near the root of the app. This wrapper uses the Next.js App Router adapter:

import type { ReactNode } from "react";
import { NuqsAdapter } from "nuqs/adapters/next/app";

export function Providers({ children }: { children: ReactNode }) {
  return <NuqsAdapter>{children}</NuqsAdapter>;
}

The nuqs adapter docs list the adapters for other routers.

Suspense for the hooks when prerendering

useDataGridUrlState and useDataGridUrlPagination read the URL in the component that calls them. On a page that prerenders, wrap that component in <Suspense>. <DataGridUrlState> has its own boundary.

Keys and prefix

The add-on writes the keys sort, group, filter, q, cols, hide, widths, and pins. prefix namespaces them, so several grids can share one page. <DataGridUrlState prefix="orders" /> writes orders_sort, orders_filter, and orders_q.

A filter group is a segment [or or [and ([notor or [notand when negated), then its rows, then a ] segment:

?filter=country:equals:X,[or,name:contains:A,name:contains:B,]

The characters [ and ] are always percent-encoded inside ids and values, so a value cannot imitate a group. A group holds one more group at most. A deeper group drops with its rows. The parser skips a stray ], closes a group left open at the end, and drops an empty group.

join=or joins the top-level entries with "or". The param is absent for "and", and any other value reads as "and". With a prefix, the param is <prefix>_join.

Behavior

  • URL params apply to the store on mount and on back and forward navigation. enableNavigationSync (default true) controls the navigation apply. A missing param keeps the initial state on mount. After navigation it clears the sort, filter, or search, and resets the layout part.
  • useDataGridUrlState() returns applyFromUrl(), the manual form of the navigation apply. Call it when the URL changed in another way, such as a framework setSearchParams. It reads the params of the current render, so call it after your router has updated them.
  • spec lists the synced parts: "sort", "group", "filter", and "search". The default is ["sort", "group"], which keeps filter values and search text out of the URL. group holds the groupBy column ids, such as ?group=region,team.
  • Writes use history: "replace" and add no history entries.
  • Sort and filter writes are immediate. The search input waits for the typing to pause (inputDebounceMs) before the store changes.
  • The grid drops a sort, group column, or filter for a removed or hidden column. It also drops one for a column that set sortable, groupable, or filterable to false. In development, a warning names each dropped column.

A hand-edited URL cannot express an unbounded view. URL state options lists every bound. The main ones:

  • The filter param reads at most 256 segments and keeps at most 64 rows and 16 groups.
  • An isAnyOf list keeps at most 1,000 values, or max(number of choices, 64) for a column with choices that no server lists. An isNoneOf list over the bound drops the whole segment.
  • A value, list entry, or range bound over 1,000 characters drops the segment.
  • The q param is cut to 500 characters.
  • The sort param reads at most 256 segments and keeps at most 64 sorts, one per column, so the first segment of a column wins.

A sort from the URL (?sort=name:asc) shows its arrow in a string header. Set headerClickBehavior="sort" to let a header click change it, or add the sort list.

A column with choices keeps the blank entry and the set filter values that match a choice or a loaded value, ignoring case. With filterMode="server" or fetchFilterValues, every value stays.

Column layout

The layout option picks which parts of the column layout go into the URL. The default is ["order", "hidden"]. Widths depend on the screen of the viewer, so widths and pins are opt-in. layout={[]} turns layout sync off. layout={["order", "hidden", "widths"]} adds the widths and writes a URL such as ?cols=city,name,age&hide=age&widths=name:240.

PartKeyFormat
ordercolsColumn ids, comma-separated.
hiddenhideColumn ids, comma-separated. - means no hidden column.
widthswidthsid:px pairs, whole pixels.
pinspinsid:s or id:e pairs. The codes l and r read as s and e. - means no pinned column.
  • A part is in the URL only while it differs from the layout the grid started with.
  • The URL changes once per committed gesture: a drop, a resize release, a pin, or a hide. A resize drag writes nothing while the pointer moves.
  • The grid drops an id that matches no column. A column missing from cols keeps its place at the end.

Pagination

useDataGridUrlPagination syncs page and pageSize with the URL, apart from <DataGridUrlState>. It returns the controlled pair page, pageSize, onPageChange, and onPageSizeChange, plus the resolved pageSizeOptions. Spread the result onto DataGridProvider. DataGridPaginationBar reads pageSizeOptions from the provider:

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
} from "@/components/data-grid/data-grid";
import {
  DataGridPaginationBar,
} from "@/components/data-grid-pagination/data-grid-pagination";
import {
  useDataGridUrlPagination,
} from "@/components/data-grid-url-state/data-grid-url-state";

type Order = { id: string };
const columns = [{ id: "id", header: "Order", accessorKey: "id" }] as const;

export function OrdersGrid({ rows }: { rows: Order[] }) {
  const pagination = useDataGridUrlPagination();

  return (
    <DataGridProvider data={rows} columns={columns} {...pagination}>
      <DataGridRoot className="h-96">
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
      <DataGridPaginationBar />
    </DataGridProvider>
  );
}

For a server grid, pass the same result into useDataGridServerRows or useDataGridServerPager. See Keep pages in URL.

page is 1-based and leaves the URL at 1. A page beyond 1,000,000 falls back to 1. pageSize leaves the URL when it equals defaultPageSize (default: the first of pageSizeOptions, 10). A pageSize outside pageSizeOptions falls back to the default. Without pageSizeOptions, the pager list 10, 25, 50, 100 is the gate. The pager clamps an out-of-range page and writes it to the URL. A change of pageSize resets the URL page to 1, because a page number fits only the size it was chosen at.

Server mode

The add-on restores sorts, filters, and search text through the store actions. Those actions call onSortChange, onFilterChange, and onSearchTextChange as any change does. With sortMode="server" and filterMode="server", a link restores the spec and the grid never reorders or hides the rows you load. useDataGridServerRows sets both modes. A grid that declares a totalRowCount holds the restored spec and never sorts or filters the partial data. Without totalRowCount and without the hook, set both modes on a scroll-mode grid. Otherwise the add-on sorts and filters the partial data on the client.

A grid that declares a totalRowCount holds the restored spec and never sorts or filters the partial data. Fetch the rows for the restored spec on mount. For page numbers in the URL, see Keep pages in URL.

A link holds up to 64 sorts. The default parseServerSpec limits accept them. In server filter mode, every set filter value stays, and your server checks the values.

With saved views

Mount <DataGridUrlState> beside the saved views add-on (data-grid-views). The URL sets the first state, and a link with a sort, filter, search, or column layout param wins over the default view. Opening a view writes its state to the URL. After back or forward, the active view stays active and shows as modified.

On this page