gridcn2.0.0
Sort, filter, and search

Saved views

Name, save, open, and share the sort, filters, search, and column layout of a grid with the data-grid-views add-on.

Users set up a grid the way they like it, then lose it on the next visit. data-grid-views saves the sort, the filters, the search text, and the column layout under a name and opens it with one click. DataGridViews is the toolbar button. useDataGridViews is the hook behind it.

Sort, filter, search, or hide a column, then open Views and save the result. Pick a view to restore it. Pick where the views live: this browser, or a simulated server with a slow async adapter.

Name
Email
Role
Score
Silent Tiger
user0@example.com
Viewer
4
Quick Lion
user1@example.com
Viewer
89
Swift Wolf
user2@example.com
Manager
80
Eager Lion
user3@example.com
User
51
Eager Tiger
user4@example.com
Viewer
83
Silent Wolf
user5@example.com
User
15
Swift Lion
user6@example.com
Viewer
62
Eager Lion
user7@example.com
Manager
42
Eager Eagle
user8@example.com
Editor
35
Bold Tiger
user9@example.com
Editor
52
Bold Bear
user10@example.com
User
28
Swift Wolf
user11@example.com
Manager
9
Swift Bear
user12@example.com
Viewer
45
Eager Wolf
user13@example.com
Editor
44
Swift Eagle
user14@example.com
Viewer
51
Quick Lion
user15@example.com
Manager
28
Bold Wolf
user16@example.com
Editor
76
Swift Eagle
user17@example.com
Admin
26
Eager Eagle
user18@example.com
Manager
70
Eager Bear
user19@example.com
Editor
67
Silent Lion
user20@example.com
Manager
89
Silent Tiger
user21@example.com
Manager
40
Eager Tiger
user22@example.com
Manager
82
Silent Lion
user23@example.com
Admin
16
Bold Eagle
user24@example.com
Admin
38
Bold Lion
user25@example.com
Viewer
3
Quick Tiger
user26@example.com
Viewer
41
Bold Eagle
user27@example.com
Editor
10
Swift Tiger
user28@example.com
Editor
6
Silent Lion
user29@example.com
Viewer
42
pnpm dlx shadcn@latest add @gridcn/data-grid-views

Place the button inside the provider:

"use client";

import {
  DataGridBody,
  DataGridHeader,
  DataGridProvider,
  DataGridRoot,
  defineColumns,
} from "@/components/data-grid/data-grid";
import {
  DataGridToolbar,
} from "@/components/data-grid-toolbar/data-grid-toolbar";
import {
  DataGridViews,
} from "@/components/data-grid-views/data-grid-views";

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

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

function OrdersGrid({ rows }: { rows: Order[] }) {
  return (
    <DataGridProvider data={rows} columns={columns}>
      <DataGridToolbar>
        <DataGridViews storage="orders-views" />
      </DataGridToolbar>
      <DataGridRoot>
        <DataGridHeader />
        <DataGridBody />
      </DataGridRoot>
    </DataGridProvider>
  );
}

With no props, views persist in localStorage under gridcn-views. Grids with the same columns can share it and stay in sync. Two mounted grids with other columns on one key warn in development, so give such a grid its own storage key. If localStorage is blocked or full, the views stay in memory for the page.

What a view holds

A view holds the sort, the groupBy columns, and the filters, with their groups, the join of the top level, and custom operators. A negated group stays negated. It holds the search text with its two options, match case and whole cell. It holds the column layout: order, hidden columns, pins, and widths. A view holds no rows, no selection, no page, and no scroll position.

Opening a view runs the same actions as a user gesture, and only for the parts that differ from the grid. The change callbacks of a controlled sortState, filterState, searchText, or columnLayout fire for those parts.

The button

The button shows the name of the active view. A "Modified" badge appears when the grid differs from that view. The popover has:

  • one row per view: open, default star, rename, and delete (the second press deletes)
  • "Update" for the active view, shown only while the grid differs from it
  • a name field and "Save as new view"
  • a text area with "Export active view" and "Import view"

Opening the active view again reverts the changes. Every control sits in the tab order of the popover. Enter saves a rename and Esc cancels it. A polite status message announces each action, and a failure shows as an alert with a Retry button.

Default view

The star marks one view as the default. After the views load, the default view applies if all of these hold:

  • enableDefaultView is not false.
  • value and defaultValue are both unset.
  • The grid still holds its first state.

A grid that something else already changed keeps its state. With both add-ons mounted, a URL state link with a param that changes the first state wins over the default view.

value and onValueChange control which view is active, and defaultValue seeds it once:

"use client";

import { useState } from "react";
import { DataGridViews } from "@/components/data-grid-views/data-grid-views";

export function ControlledViews() {
  const [viewId, setViewId] = useState<string | null>(null);

  return <DataGridViews value={viewId} onValueChange={setViewId} />;
}

When value changes, the hook opens that view. A pick only calls onValueChange. The grid changes when you pass the new value back. Saving or importing a view opens it at once and then calls onValueChange with its id.

Storage

A storage adapter has two functions. load returns the stored document, or undefined for none. save receives the whole document. Both can be async. load gets a signal that aborts on unmount. The hook checks everything that load returns, so a hand-edited document cannot break the grid.

Throw from load when the store cannot be read. The popover then shows a Retry button and runs no save, so the stored views stay safe. A document with an unknown version counts as a read failure. The grid never saves a document over 1,000,000 characters.

This adapter keeps the views on your server:

import type {
  DataGridViewsStorage,
} from "@/components/data-grid-views/data-grid-views";

const serverViews: DataGridViewsStorage = {
  load: async ({ signal }) => {
    const response = await fetch("/api/grid-views/orders", { signal });
    if (response.status === 404) return undefined;
    if (!response.ok) throw new Error("Loading views failed");
    return response.json();
  },
  save: async (document) => {
    const response = await fetch("/api/grid-views/orders", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(document),
    });
    if (!response.ok) throw new Error("Saving views failed");
  },
};

Pass it as storage. A thrown error from save shows in the popover with a Retry button, and onError receives it. The change stays on screen. Saves that start while another save runs collapse into one, so the last document wins. createLocalStorageViewsStorage(key) is the default adapter. createMemoryViewsStorage(seed?) keeps views for the life of the page.

The default adapter listens to the storage event, so a save in one tab reloads the views of another tab on the same key. A custom adapter that offers subscribe gets the same reload.

Share a view as text

"Export active view" writes the view as JSON into the text area. "Import view" reads that text and adds it as a new view. Import bounds the text and checks it against the live columns:

  • Import refuses text over 100,000 characters, and anything but a gridcn view file.
  • An entry for a column that does not exist, or that opted out with sortable, groupable, or filterable set to false, goes away. A sort or filter on a column that the file hides goes away too. The status message reports how many entries it left out.
  • A built-in operator with a value of the wrong shape goes away. An operator that a column or its cell type registers in filter.operators keeps a value of the shape its input names. Any other shape drops the filter.
  • A column with choices keeps the blank entry and the set filter values that match a choice or a loaded value. The match ignores case. With filterMode="server" or fetchFilterValues, the server lists the values, so every value stays.
  • An isAnyOf list is cut to 1,000 entries. An isNoneOf list or a custom operator list over 1,000 entries drops the filter.
  • A view keeps at most 64 sorts, 4 group columns, 64 filters, and 16 filter groups. A filter value over 1,000 characters drops the filter.
  • The name of a view has at most 80 characters, and a stored view needs an id of at most 64 characters.
  • A column id has no length limit. A stored view keeps ids of columns the grid lacks, and applying the view skips them. A column width over 10,000 px goes away. Each layout list is cut to 1,000 entries. The search text is cut to 500 characters. The document keeps at most 50 views.

Use the hook

useDataGridViews(options) takes the options of the button and returns the state and the actions for your own UI. Call it inside the provider. The full lists are on Saved views options:

"use client";

import { useDataGridViews } from "@/components/data-grid-views/data-grid-views";

export function SaveViewButton() {
  const views = useDataGridViews({ storage: "orders-views" });

  return <button onClick={() => views.saveView("My view")}>Save</button>;
}

Limits

A save never cuts a view. overLimit names the part that is over a limit. It is "sorts", "filters", "search", or "layout". A sort, filter, or layout entry for a column that the grid lacks is not over a limit.

A filter whose value does not fit its operator, such as a list on contains, also counts as over the "filters" limit. Only code builds such a filter: setFilters, filterState, or defaultFilterState. A filter without a value on an operator that takes one, such as equals, is not over a limit.

"Save as new view" and "Update" are off with a line for that part. saveView returns null and updateView returns false.

Server mode

A view stores the grid state only, so it works in every data mode:

  • Local array and client pagination. Opening a view sorts and filters the local rows again.
  • Server pagination and scroll mode with sortMode="server" or filterMode="server". Opening a view calls onSortChange, onFilterChange, and onSearchTextChange for the parts that differ, and useDataGridServerRows sends the new spec. Every set filter value stays, and your server checks the values.
  • Controlled state. Your props receive the change callbacks.

A view saves no page number. A view that changes the sort, the filters, or the search text sends server rows back to page 1. A layout-only view keeps the page.

On this page