ProGridSign in

Features

Saved views

Save named arrangements of columns, sort, filters, grouping, aggregations and pivot, and switch between them from the toolbar — including layouts that leave the reader's filters alone, so the same rows can be read several ways.

Turn them on

views adds a menu beside the grid’s title. It shows the active view’s name, switches between views, saves the current one, and renames or deletes it. With views set to true, the grid keeps the list in localStorage under persist.key (or views.storageKey).

<ProGrid
  columns={columns}
  data={orders}
  getRowId={(order) => order.id}
  persist={{ key: "orders-grid", local: true }}
  views // kept in localStorage under persist.key
/>
Live demo

Filter once, read it several ways

Filter the orders — type in the bar, or pick statuses — then switch between Revenue by region and Largest orders by status. The rows stay filtered; only the layout changes. Needs attention is a filter view instead. Save your own from the menu and reload: it stays.

import { ProGrid, type GridView, type ProColumnDef } from "@/components/pro-grid"
import { formatCurrency, operationOrders, type OperationOrder } from "@/lib/operations-data"

function StatusCell({ value }: { value: unknown }) {
  const status = String(value)
  return <span className={`order-status order-status--${status.toLowerCase().replaceAll(" ", "-")}`}>{status}</span>
}

const baseColumns: ProColumnDef<OperationOrder>[] = [
  { accessorKey: "id", header: "Order", size: 118, meta: { label: "Order", type: "string" } },
  { accessorKey: "customer", header: "Customer", size: 190, meta: { label: "Customer", type: "string" } },
  {
    accessorKey: "region",
    header: "Region",
    size: 145,
    meta: {
      label: "Region",
      type: "string", filterVariant: "set",
      filterOptions: ["North America", "Europe", "Asia Pacific", "Latin America"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "status",
    header: "Status",
    size: 120,
    cell: ({ getValue }) => <StatusCell value={getValue()} />,
    meta: {
      label: "Status",
      type: "string", filterVariant: "set",
      filterOptions: ["On track", "At risk", "Delayed", "Complete"],
      groupable: true,
      pivotable: true,
    },
  },
  {
    accessorKey: "units",
    header: "Units",
    size: 88,
    meta: { label: "Units", type: "number", align: "right", aggregable: true, defaultAgg: "sum" },
  },
  {
    accessorKey: "revenue",
    header: "Revenue",
    size: 128,
    meta: {
      label: "Revenue",
      type: "number",
      align: "right",
      aggregable: true,
      defaultAgg: "sum",
      formatValue: (value) => formatCurrency(Number(value)),
    },
  },
]

const groupingDemoRows = operationOrders.slice(0, 60)

/**
 * Two kinds of view: layouts that rearrange whatever is filtered — they carry
 * columns, grouping and aggregations but no filters — and one that is a filter
 * in its own right. Defined in code, so they are presets: a reader can apply
 * and copy them, and saves their own beside them.
 */
const viewsDemoPresets: GridView[] = [
  {
    id: "revenue-by-region",
    name: "Revenue by region",
    parts: ["columns", "group", "aggregations"],
    state: {
      grouping: ["region"],
      aggregations: { revenue: "sum", units: "avg" },
      columnVisibility: { id: false },
    },
  },
  {
    id: "units-by-status",
    name: "Largest orders by status",
    parts: ["columns", "group", "aggregations"],
    state: {
      grouping: ["status"],
      aggregations: { units: "max", revenue: "max" },
      columnVisibility: { customer: false },
    },
  },
  {
    id: "needs-attention",
    name: "Needs attention",
    parts: ["filters", "sort"],
    state: {
      columnFilters: [
        { id: "status", type: "string", join: "AND", conditions: [{ operator: "in", value: ["At risk", "Delayed"] }] },
      ],
      quickFilter: "",
      sorting: [{ id: "revenue", desc: true }],
    },
  },
]

export function ViewsDocsDemo() {
  return (
    <ProGrid<OperationOrder>
      columns={baseColumns}
      data={groupingDemoRows}
      getRowId={(row) => row.id}
      height={390}
      filters
      title="Orders"
      toolbar={{ chart: false, refresh: false, pivot: false }}
      views={{ storageKey: "docs-saved-views", presets: viewsDemoPresets }}
    />
  )
}

Orders

FiltersNo filters yet — add one →
Order
Customer
Region
Status
Units
Revenue
Total
Sum13230
Sum$2,811,630
60 rows

A view writes only the parts it carries

Every view lists its parts, and applying it changes those parts and nothing else. A view saved without filters is a layout. It regroups, re-aggregates and rearranges the rows the reader already filtered, instead of replacing their filters. A view saved with only filters and sort works the other way: it changes which rows are shown and leaves the layout alone. The save form lets the reader choose the parts, and the menu lists each view’s parts under its name. That way the reader can see whether a view will touch their filters before picking it.

type GridViewPart = "columns" | "sort" | "filters" | "group" | "aggregations" | "pivot"

type GridView = {
  id: string
  name: string
  parts: GridViewPart[] // what applying it writes — nothing else is touched
  state: GridViewState  // the state of exactly those parts
}
What each part of a view covers
PartCovers
columnsColumn order, visibility, widths and pinning
sortThe sort
filtersColumn filters and the quick filter, plus hostFilters when given
groupRow grouping
aggregationsThe aggregation picked in each column's menu
pivotPivot mode and its configuration (not which groups are open)

A part is offered only where the grid can use it. filters needs something to filter with: the quick filter, a filterable column with funnels or a filter surface, filters you control through state, or hostFilters. group needs a groupable column, aggregations needs an aggregable one, and pivot needs the pivot toggle. Page and selection are never part of a view.

Where the grid’s wording would mislead, partText rewords a part in the menu and the save form. For example, a screen whose filters live in a sidebar can say { filters: { hint: "The sidebar's filters" } }.

Keeping the reader’s filters

The menu has a Keep current filters switch. While it is on, picking any view skips that view’s filters, so even a full snapshot only changes the layout. Filters skipped this way don’t mark the view as modified, and “Save changes” keeps the view’s own filters instead of writing in the ones the reader is using.

Some screens get their filters from somewhere else: a customer picked on the page, a URL, a parent selection. Set keepFilters there to fix the behaviour. The switch is hidden and views only ever rearrange.

// The filters on this screen come from the page — a customer picked elsewhere —
// so views here only ever rearrange. The switch is hidden and always on.
<ProGrid
  columns={columns}
  data={ordersForCustomer}
  state={{ columnFilters: customerFilters }}
  onStateChange={sync}
  views={{ items, onChange, keepFilters: true }}
/>

To keep the switch in your own state instead, pass onKeepFiltersChange with keepFilters. The switch stays in the menu, shows your value, and reports each flip.

// The switch stays the reader's, but the screen remembers it with its own settings.
const [keep, setKeep] = useState(settings.keepFilters)

<ProGrid
  columns={columns}
  data={orders}
  views={{ keepFilters: keep, onKeepFiltersChange: setKeep }}
/>

Filters outside the grid

Some screens filter outside the grid: a sidebar, a date range in the page header, a search the API runs. hostFilters lets views carry those filters with the grid’s own. Saving a view with filters also stores value. Applying the view’s filters hands the stored value to apply, including when the reader picks the active view again to discard their changes. When value changes, the active view is marked modified, and “Save changes” stores the new value. “Keep current filters” holds these filters back too.

// The sidebar decides which rows the API returns; the grid never sees it.
const [sidebar, setSidebar] = useState<SidebarFilter[]>([])

<ProGrid
  columns={columns}
  dataSource={dataSource(sidebar)}
  views={{
    hostFilters: {
      value: sidebar,
      // Saved as JSON reads it back, so dates arrive as ISO strings.
      apply: (saved) => setSidebar(reviveDates(saved as SidebarFilter[])),
    },
    partText: { filters: { hint: "The sidebar's filters" } },
  }}
/>

The value is stored the way JSON reads it back, right from the first save. A Date becomes its ISO string, so apply always receives the same shape, before a reload and after. Views are compared as JSON with sorted keys, so a live Date matches the string it was saved as. Pass equals when some fields shouldn’t count, such as a sidebar’s open or closed state.

Presets

presets are views your code defines. They are listed first, under their own heading. A reader can apply a preset and save a copy of it, but can’t rename, overwrite or delete it. Presets aren’t stored, so changing one in code changes it for every reader.

const presets: GridView[] = [
  {
    id: "revenue-by-region",
    name: "Revenue by region",
    // No "filters": applying this regroups whatever the reader has filtered.
    parts: ["columns", "group", "aggregations"],
    state: {
      grouping: ["region"],
      aggregations: { revenue: "sum", units: "avg" },
      columnVisibility: { id: false },
    },
  },
  {
    id: "needs-attention",
    name: "Needs attention",
    // A filter in its own right, which leaves the layout alone.
    parts: ["filters", "sort"],
    state: {
      columnFilters: [
        { id: "status", type: "string", join: "AND", conditions: [{ operator: "in", value: ["At risk", "Delayed"] }] },
      ],
      quickFilter: "",
      sorting: [{ id: "revenue", desc: true }],
    },
  },
]

<ProGrid columns={columns} data={orders} views={{ presets, storageKey: "orders" }} />

Keeping views in your own store

To keep the views in your own store (a table per user, an API), pass items and onChange. The grid then stores nothing itself. onChange receives the whole next list after every save, update, rename or delete. Fields of your own on a view, such as an owner or a shared flag, are kept through those changes. An items list without onChange is read-only: readers can switch views but not save them.

const [views, setViews] = useState<GridView[]>([])
const [activeId, setActiveId] = useState<string | null>(null)

useEffect(() => {
  fetch("/api/me/grid-views/orders").then((r) => r.json()).then(setViews)
}, [])

<ProGrid
  columns={columns}
  data={orders}
  views={{
    items: views,
    onChange: (next) => {
      setViews(next) // the whole next list, after a save, rename or delete
      void fetch("/api/me/grid-views/orders", { method: "PUT", body: JSON.stringify(next) })
    },
    activeId,
    onActiveChange: (id) => setActiveId(id),
  }}
/>

A picker of your own

The built-in menu runs on a controller, and the toolbar and footer slots receive the same controller as views. A picker of your own calls the same apply, save, update, rename and remove the menu does, and reads the same active and modified, so the two always agree. The menu itself is exported as ProGridViewsMenu, for placing it somewhere else.

<ProGrid
  columns={columns}
  data={orders}
  views={{ presets }}
  toolbar={{ views: false }} // the built-in button goes; the controller stays
  renderToolbar={({ views }) =>
    views && (
      <div className="flex gap-1">
        {views.views.map((view) => (
          <button
            key={view.id}
            aria-pressed={views.active?.id === view.id}
            onClick={() => views.apply(view.id)}
          >
            {view.name}
            {views.active?.id === view.id && views.modified && " •"}
          </button>
        ))}
        <button onClick={() => views.save(prompt("Name") ?? "", ["columns", "group", "aggregations"])}>
          Save layout
        </button>
      </div>
    )
  }
/>

// Or keep the built-in menu and move it into a slot of your own:
renderToolbarEnd={({ views }) => views && <ProGridViewsMenu controller={views} />}

The handle has the two primitives underneath, for a UI that lives outside the grid entirely:

const grid = useRef<ProGridHandle<Order>>(null)

// A snapshot of some parts of the current state — not added to any list.
const layout = grid.current.captureView({ name: "Mine", parts: ["columns", "group", "aggregations"] })

// Apply a view on your own terms: by object or by id, narrowed or held back.
grid.current.applyView(layout)
grid.current.applyView("needs-attention", { keep: ["filters"] })
grid.current.applyView(fullView, { only: ["columns"] })

Views outlive their columns

A view can outlive the columns it was saved against: fields get renamed and permissions hide columns. Before it is applied, a view goes through the same checks a persisted layout does. Sorts, filters, groups and aggregations on columns that no longer exist (or can no longer be grouped or aggregated) are dropped, and the rest of the view still applies. In development the grid warns about each dropped item. “Reset settings” clears which view is active but keeps the saved views. The reader made them, so they aren’t settings.