# React Native Data Grid (Pro)

> A React Native data grid for iOS, Android and the web at the level of AG Grid and MUI X: virtualized rows for 10,000+, server-side and infinite modes, typed columns (currency, dates, status, tags, avatars, progress, ratings, sparklines), multi-sort, a filter builder with and/or, quick filters with counts, grouping with subtotals, tree data, master-detail, column drag, pin and fit, spreadsheet keyboard with copy, inline editing with validation and undo, saved views, row actions and CSV export. Cards and a filter sheet on phones. Part of Patine Pro, React Native core only.

# DataGrid Pro

`DataGrid` is the table a back office lives in. Columns have types, so a currency column formats, sums, filters by range and edits as a number without extra code. It sorts by several columns, filters with a rule builder ("Stage is any of Lead, Qualified **and** Value > 10,000"), groups with subtotals, shows tree rows and detail panels, and saves all of it as named views. Rows are virtualized, so 10,000 of them scroll smoothly, or the grid hands search, sort, filters and pages to your server. On the web it works like a spreadsheet: arrow keys, ranges, ⌘C, typing to edit, ⌘Z. On phones each row becomes a card, with every filter in a sheet.

It's part of Patine Pro and uses React Native core only. For a few rows of static data, use the free [Table](../components/table).

```tsx
import { DataGrid } from '@patine-ui/pro';
```

```tsx live full
import { DataGrid } from '@patine-ui/pro';

const FIRST = ['Maya', 'Leo', 'Ana', 'Noah', 'Ivy', 'Omar', 'Zoe', 'Liam', 'Sara', 'Eli', 'Nina', 'Theo'];
const LAST = ['Cohen', 'Park', 'Silva', 'Novak', 'Reyes', 'Haddad', 'Kim', 'Moreau', 'Berg', 'Rossi'];
const COMPANIES = ['Acme', 'Globex', 'Initech', 'Umbrella', 'Hooli', 'Stark', 'Wayne', 'Wonka', 'Pied Piper', 'Soylent'];
const STAGES = ['Lead', 'Qualified', 'Proposal', 'Customer', 'Churned'];
const TAGS = ['enterprise', 'smb', 'partner', 'upsell', 'at risk', 'EMEA', 'NA'];
const rand = (i, n) => Math.floor(((Math.sin(i * 9973.13) + 1) / 2) * 1e6) % n;
const day = (back) => new Date(2026, 10, 18 - back);

const CONTACTS = Array.from({ length: 64 }, (_, i) => {
  const first = FIRST[rand(i, FIRST.length)];
  const last = LAST[rand(i + 7, LAST.length)];
  const company = COMPANIES[i % COMPANIES.length];
  return {
    id: `C-${2100 + i}`,
    name: `${first} ${last}`,
    email: `${first.toLowerCase()}@${company.toLowerCase().replace(' ', '')}.com`,
    company,
    stage: STAGES[rand(i + 3, STAGES.length)],
    value: 1200 + rand(i + 11, 48000),
    score: 1 + rand(i + 5, 5),
    lastContact: day(rand(i + 2, 60)),
    tags: [...new Set([TAGS[rand(i, 7)], TAGS[rand(i + 9, 7)]])],
    activity: Array.from({ length: 12 }, (_, k) => 4 + rand(i * 12 + k, 20)),
    owner: ['Maya Cohen', 'Leo Park', 'Ana Silva'][i % 3],
  };
});

export default function Contacts() {
  return (
    <DataGrid
      title="Contacts"
      rows={CONTACTS}
      rowKey={(r) => r.id}
      accessibilityLabel="Contacts"
      pageSize={10}
      quickFilters={[
        { key: 'all', label: 'All' },
        { key: 'open', label: 'Open deals', match: (r) => ['Qualified', 'Proposal'].includes(r.stage) },
        { key: 'customers', label: 'Customers', match: (r) => r.stage === 'Customer' },
        { key: 'churned', label: 'Churned', match: (r) => r.stage === 'Churned' },
      ]}
      views={[
        { id: 'pipeline', name: 'Big deals', state: { sort: [{ key: 'value', direction: 'desc' }], filter: { logic: 'and', rules: [{ id: 'r1', field: 'value', operator: 'gt', value: '20000' }] } } },
        { id: 'owners', name: 'By owner', state: { groupBy: ['owner'], hidden: ['activity'] } },
      ]}
      bulkActions={[
        { label: 'Email', icon: 'mail', onPress: () => {} },
        { label: 'Delete', icon: 'trash', destructive: true, onPress: () => {} },
      ]}
      rowActions={(r) => [
        { label: 'Open profile', icon: 'user', onPress: () => {} },
        { label: `Email ${r.name.split(' ')[0]}`, icon: 'mail', onPress: () => {} },
        { label: 'Delete', icon: 'trash', destructive: true, onPress: () => {} },
      ]}
      columns={[
        { key: 'name', title: 'Name', type: 'avatar', value: (r) => r.name, subtitle: (r) => r.email, pinned: true, width: 230 },
        { key: 'company', title: 'Company', value: (r) => r.company, width: 130 },
        {
          key: 'stage',
          title: 'Stage',
          type: 'status',
          value: (r) => r.stage,
          options: STAGES,
          variants: { Lead: 'secondary', Qualified: 'default', Proposal: 'warning', Customer: 'success', Churned: 'destructive' },
          width: 130,
        },
        { key: 'value', title: 'Deal value', type: 'currency', value: (r) => r.value, aggregate: 'sum', width: 140 },
        { key: 'score', title: 'Lead score', type: 'rating', value: (r) => r.score, width: 130 },
        { key: 'lastContact', title: 'Last contact', type: 'date', value: (r) => r.lastContact, width: 140 },
        { key: 'tags', title: 'Tags', type: 'tags', value: (r) => r.tags, width: 190 },
        { key: 'activity', title: 'Activity', type: 'sparkline', value: (r) => r.activity.at(-1), series: (r) => r.activity, width: 130 },
        { key: 'owner', title: 'Owner', type: 'select', value: (r) => r.owner, width: 140 },
      ]}
    />
  );
}
```

Try it: shift-click a second header to sort by both, open **Filters** to add a rule, switch to the **By owner** view, tick a page of rows and select all 64, or click a cell and use the arrow keys.

## Example: a store's order queue

The orders page of a shop's admin: filter by status, tick the paid orders and mark them shipped in one go, and open a row for its shipping address.

```tsx live wide
import { useState } from 'react';
import { Badge, Text } from 'patine-ui';
import { DataGrid } from '@patine-ui/pro';

const STATUSES = ['Paid', 'Shipped', 'Refunded'];
const BADGE = { Paid: 'warning', Shipped: 'success', Refunded: 'secondary' } as const;
const PEOPLE = ['Sara Kim', 'Diego Alvarez', 'Hannah Okafor', 'Tomás Rivera', 'Mei Lin', 'Jonas Weber', 'Priya Nair', 'Lucas Moreau'];
const CITIES = ['Portland, OR', 'Austin, TX', 'Toronto, ON', 'Denver, CO', 'Brooklyn, NY', 'Berlin', 'Seattle, WA', 'Lyon'];
const FIRST = Array.from({ length: 24 }, (_, i) => ({
  id: `#${48213 - i * 7}`,
  customer: PEOPLE[i % PEOPLE.length],
  city: CITIES[(i * 3) % CITIES.length],
  items: (i % 4) + 1,
  total: [164, 78, 92, 145, 32, 219, 58, 110][i % 8] + (i % 3) * 12,
  status: i < 9 ? 'Paid' : i % 11 === 0 ? 'Refunded' : 'Shipped',
}));
type Order = (typeof FIRST)[number];

export default function Example() {
  const [orders, setOrders] = useState(FIRST);
  const ship = (ids: string[]) => setOrders((all) => all.map((o) => (ids.includes(o.id) ? { ...o, status: 'Shipped' } : o)));
  return (
    <DataGrid
      title="Orders"
      rows={orders}
      rowKey={(o: Order) => o.id}
      accessibilityLabel="Orders"
      pageSize={8}
      bulkActions={[{ label: 'Mark as shipped', icon: 'truck', onPress: ship }]}
      renderExpanded={(o: Order) => <Text size="sm">{`Ship to ${o.customer}, ${o.city} · ${o.items} item${o.items > 1 ? 's' : ''}`}</Text>}
      columns={[
        { key: 'id', title: 'Order', value: (o: Order) => o.id, pinned: true, width: 110, filter: 'text' },
        { key: 'customer', title: 'Customer', value: (o: Order) => o.customer, width: 180, filter: 'text' },
        {
          key: 'status',
          title: 'Status',
          value: (o: Order) => o.status,
          filter: STATUSES,
          render: (o: Order) => <Badge variant={BADGE[o.status as keyof typeof BADGE]}>{o.status}</Badge>,
        },
        { key: 'total', title: 'Total', value: (o: Order) => o.total, align: 'right', render: (o: Order) => <Text size="sm">{`$${o.total.toFixed(2)}`}</Text> },
      ]}
    />
  );
}
```

## Columns

Each column says what its cell holds with `value`: the grid sorts, filters, searches, groups, sums and exports by it. Give it a `type` and it draws, filters and edits that kind of value; give it `render` to draw it yourself.

| `type` | Holds | Draws | Filter row | Editor |
| --- | --- | --- | --- | --- |
| `text` (default) | a string | the text | contains | text box |
| `number` | a number | `12,400` | min – max | number box |
| `currency` | whole units (`1299.5`) and `currency` | `$1,299.50` | min – max | number box |
| `percent` | a ratio (`0.42`) | `42%` | min – max (in %) | number box (`42%`) |
| `progress` | a ratio, full at `max` (`1`) | a bar and the percent | min – max | number box |
| `rating` | `0` to `max` (`5`) | stars | min – max | stars |
| `date` | a `Date` or `YYYY-MM-DD` | `Nov 12, 2026` | Today, last 7 / 30 / 90 days… | date box and calendar |
| `boolean` | `true` / `false` | a check | Yes / No | press or Space flips it |
| `select` | one of `options` | a chip | pick, with counts | menu |
| `status` | one of `options` | a badge in its `variants` color | pick, with counts | menu |
| `multiSelect`, `tags` | some of `options` | chips, `+2` | has any, with counts | menu |
| `avatar` | a name, with `image` and `subtitle` | a picture, the name and a second line | contains | text box |
| `link` | the text, with `href` | a link that opens it | contains | text box |
| `sparkline` | a number to sort by, with `series` | a trend, green up, red down | | |

- `format` changes the text a type shows; `align`, `width`, `minWidth` and `sortable: false` do what they say.
- `filter: 'text'` or `filter: ['paid', 'overdue']` sets the filter row's control yourself; `filter: false` removes it.
- `pinned: true` (or `'left'`) keeps a column at the start, `pinned: 'right'` at the end, while the rest scroll sideways.
- `hidden` hides it at first; the **Columns** menu shows it again.

### Moving, pinning and fitting columns

On the web, drag a header sideways to move its column, drag its edge to resize it, and double-click the edge to fit the content. Every header has a menu (⋮) to sort, pin left or right, filter, group by, fit and hide. The **Columns** menu lists every column with a handle to drag it into place, a box to show it, and buttons to pin it.

## Sorting

Press a header to sort by it, again to reverse, again to stop. Shift-press another to add it: the grid sorts by the first, then the second, and numbers each header. Text sorts naturally ("Item 2" before "Item 10"), dates by day, and empty cells go last either way. `initialSort` takes one sort or a list.

## Filtering

Three ways to narrow, and they combine:

- **Quick filters**: tabs over the grid with live counts, from `quickFilters`.
- **The filter row**: a control under each header (the filter button beside **Filters**). Options show how many rows hold each, counted against the other filters.
- **The filter builder**: **Filters** opens rules of field, operator and value, joined by "and" or "or". The operators follow the type: contains, starts with, is empty for text; =, >, is between for numbers; is before, is after for dates; is any of, has all of for options and tags.

What's on shows as chips over the grid, each with an ✕. A rule still being filled in doesn't filter yet.

## Grouping and totals

Group by one column or several from **Group by** in the toolbar or a header's menu. Each group row folds open and shut and shows its count and each column's `aggregate`: `sum`, `avg`, `min`, `max` or `count`. A totals row stays at the foot while you scroll. `renderExpanded` adds a detail panel under each row, here the order's line items.

```tsx live full
import { Text } from 'patine-ui';
import { DataGrid } from '@patine-ui/pro';

const STATUS = ['Paid', 'Fulfilled', 'Pending', 'Refunded'];
const CHANNELS = ['Online store', 'Instagram', 'Marketplace', 'Wholesale'];
const NAMES = ['Ava Brooks', 'Kai Tanaka', 'Mila Novak', 'Jonah Reed', 'Lena Fischer', 'Ravi Shah', 'Chloe Martin', 'Diego Ruiz'];
const ITEMS = ['Linen shirt', 'Wool scarf', 'Canvas tote', 'Leather belt', 'Desk lamp', 'Ceramic mug'];
const rand = (i, n) => Math.floor(((Math.sin(i * 7919.7) + 1) / 2) * 1e6) % n;

const ORDERS = Array.from({ length: 120 }, (_, i) => {
  const lines = 1 + rand(i, 3);
  const items = Array.from({ length: lines }, (_, k) => ({ name: ITEMS[rand(i * 3 + k, ITEMS.length)], qty: 1 + rand(i + k, 3), price: 18 + rand(i * 7 + k, 140) }));
  return {
    id: `#${48210 + i}`,
    customer: NAMES[rand(i + 4, NAMES.length)],
    channel: CHANNELS[rand(i + 1, CHANNELS.length)],
    status: STATUS[rand(i + 2, STATUS.length)],
    placed: new Date(2026, 10, 18 - rand(i + 6, 45)),
    items,
    total: items.reduce((s, it) => s + it.qty * it.price, 0),
  };
});

export default function Orders() {
  return (
    <DataGrid
      title="Orders"
      rows={ORDERS}
      rowKey={(r) => r.id}
      accessibilityLabel="Orders"
      initialGroupBy={['status']}
      paging="scroll"
      height={520}
      renderExpanded={(r) => (
        <View style={{ gap: 6, maxWidth: 420 }}>
          {r.items.map((it, k) => (
            <View key={k} style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
              <Text size="sm">{`${it.qty} × ${it.name}`}</Text>
              <Text size="sm" color="textSecondary">{`$${(it.qty * it.price).toFixed(2)}`}</Text>
            </View>
          ))}
        </View>
      )}
      columns={[
        { key: 'id', title: 'Order', value: (r) => r.id, width: 110, aggregate: 'count' },
        { key: 'customer', title: 'Customer', type: 'avatar', value: (r) => r.customer, width: 190 },
        { key: 'channel', title: 'Channel', type: 'select', value: (r) => r.channel, options: CHANNELS, width: 150 },
        { key: 'status', title: 'Status', type: 'status', value: (r) => r.status, options: STATUS, variants: { Paid: 'success', Fulfilled: 'default', Pending: 'warning', Refunded: 'destructive' }, width: 130 },
        { key: 'placed', title: 'Placed', type: 'date', value: (r) => r.placed, width: 140 },
        { key: 'items', title: 'Items', type: 'number', value: (r) => r.items.reduce((s, it) => s + it.qty, 0), aggregate: 'sum', width: 100 },
        { key: 'avg', title: 'Avg item', type: 'currency', value: (r) => r.total / r.items.reduce((s, it) => s + it.qty, 0), aggregate: 'avg', width: 130 },
        { key: 'total', title: 'Total', type: 'currency', value: (r) => r.total, aggregate: 'sum', width: 140 },
      ]}
    />
  );
}
```

## Editing

Mark a column `editable` and pass `onCellChange`: it gets the row, the column's key and the typed value. On the web double-click a cell, press Enter, or just start typing; on phones long-press it. Enter saves and moves down, Tab saves and moves right, Escape puts the value back. `validate` returns a message for a value that can't be saved, and the cell stays open in red with the reason. Numbers and dates are checked as well. ⌘Z (or **Undo**) takes edits back one at a time.

```tsx live full
import { DataGrid } from '@patine-ui/pro';

const PRODUCTS = [
  ['Aero running shoe', 'Footwear', 129, 42, 60],
  ['Trail jacket', 'Outerwear', 249, 8, 25],
  ['Merino base layer', 'Apparel', 89, 0, 40],
  ['Daypack 22L', 'Bags', 119, 31, 30],
  ['Insulated bottle', 'Gear', 34, 120, 100],
  ['Camp stove', 'Gear', 79, 14, 20],
  ['Rain shell', 'Outerwear', 189, 5, 25],
  ['Wool beanie', 'Apparel', 29, 64, 50],
].map(([name, category, price, stock, target], i) => ({
  sku: `SKU-${3100 + i}`,
  name,
  category,
  price,
  stock,
  target,
  active: stock > 0,
  restock: `2026-12-${String(2 + i * 3).padStart(2, '0')}`,
}));

export default function Inventory() {
  const [rows, setRows] = useState(PRODUCTS);
  return (
    <DataGrid
      title="Inventory"
      rows={rows}
      rowKey={(r) => r.sku}
      accessibilityLabel="Inventory"
      defaultDensity="compact"
      onCellChange={(row, key, value) => setRows((all) => all.map((r) => (r.sku === row.sku ? { ...r, [key]: value } : r)))}
      columns={[
        { key: 'sku', title: 'SKU', value: (r) => r.sku, width: 110, pinned: true },
        { key: 'name', title: 'Product', value: (r) => r.name, editable: true, width: 200, validate: (v) => (String(v ?? '').trim() ? undefined : 'A product needs a name') },
        { key: 'category', title: 'Category', type: 'select', value: (r) => r.category, options: ['Apparel', 'Bags', 'Footwear', 'Gear', 'Outerwear'], editable: true, width: 140 },
        { key: 'price', title: 'Price', type: 'currency', value: (r) => r.price, editable: true, width: 120, validate: (v) => (v > 0 ? undefined : 'Price must be above 0') },
        { key: 'stock', title: 'In stock', type: 'number', value: (r) => r.stock, editable: true, aggregate: 'sum', width: 110, validate: (v) => (Number.isInteger(v) && v >= 0 ? undefined : 'Whole units, 0 or more') },
        { key: 'level', title: 'Stock level', type: 'progress', value: (r) => Math.min(1, r.stock / r.target), width: 160 },
        { key: 'active', title: 'Listed', type: 'boolean', value: (r) => r.active, editable: true, width: 90, align: 'center' },
        { key: 'restock', title: 'Restock', type: 'date', value: (r) => r.restock, editable: true, width: 150 },
      ]}
    />
  );
}
```

`onCellEdit(row, key, text)` from earlier versions still works and gets the value as text.

## Keyboard

Click a cell, or Tab into the grid, and it works like a spreadsheet:

| Keys | Does |
| --- | --- |
| Arrows | Move the focused cell. With Shift, extend a range |
| Tab, Shift-Tab | Next or previous cell, wrapping to the next row |
| Home, End | The row's first or last cell. With ⌘ / Ctrl, the grid's |
| Page Up, Page Down | Ten rows up or down |
| Enter, F2 | Edit the cell, or open the row when it isn't editable |
| Typing | Replaces the value and starts editing |
| Delete, Backspace | Clears an editable cell |
| Space | Ticks the row, or flips a yes / no cell |
| ⌘C / Ctrl-C | Copies the range as tab-separated text, ready to paste in a spreadsheet |
| ⌘A, ⌘Z | Selects every cell; undoes the last edit |
| Escape | Drops the range |

## Row actions and selection

`rowActions` adds a ⋯ menu at the end of each row (pinned to the right edge on the web, at the foot of each card on phones). `bulkActions` adds checkboxes: ticking rows turns the toolbar into a bar of your actions. Ticking a whole page offers **Select all 1,204**, which ticks every match across pages; each action gets the ids and `{ all }`, which in server mode tells you to act on the whole query. `onRowReorder` adds a grip to drag rows into order, while nothing is sorted, filtered or grouped.

```tsx live full
import { DataGrid } from '@patine-ui/pro';

const PEOPLE = ['Hannah Lee', 'Marco Bianchi', 'Priya Nair', 'Tom Walsh', 'Yara Haddad', 'Felix Wagner', 'Grace Kim', 'Sam Ortiz', 'Nora Lind', 'Ben Adler', 'Iris Moreau', 'Kenji Mori'];
const ROLES = ['Owner', 'Admin', 'Editor', 'Viewer'];
const USERS = PEOPLE.map((name, i) => ({
  id: `u${i + 1}`,
  name,
  email: `${name.split(' ')[0].toLowerCase()}@northwind.io`,
  role: ROLES[Math.min(3, Math.floor(i / 3))],
  status: ['active', 'active', 'invited', 'active', 'paused'][i % 5],
  mfa: i % 4 !== 2,
  seen: new Date(2026, 10, 18 - ((i * 5) % 30)),
}));

export default function Members() {
  const [users, setUsers] = useState(USERS);
  const remove = (ids) => setUsers((all) => all.filter((u) => !ids.includes(u.id)));
  return (
    <DataGrid
      title="Members"
      rows={users}
      rowKey={(r) => r.id}
      accessibilityLabel="Members"
      pageSize={6}
      onRowReorder={(id, to) =>
        setUsers((all) => {
          const next = all.filter((u) => u.id !== id);
          next.splice(to, 0, all.find((u) => u.id === id));
          return next;
        })
      }
      bulkActions={[
        { label: 'Resend invite', icon: 'send', onPress: () => {} },
        { label: 'Remove', icon: 'trash', destructive: true, onPress: (ids) => remove(ids) },
      ]}
      rowActions={(u) => [
        { label: 'Edit role', icon: 'userCog', onPress: () => {} },
        { label: 'Reset password', icon: 'key', onPress: () => {} },
        { label: u.status === 'paused' ? 'Reactivate' : 'Suspend', icon: 'pause', onPress: () => setUsers((all) => all.map((x) => (x.id === u.id ? { ...x, status: x.status === 'paused' ? 'active' : 'paused' } : x))) },
        { label: 'Remove from workspace', icon: 'trash', destructive: true, disabled: u.role === 'Owner', onPress: () => remove([u.id]) },
      ]}
      columns={[
        { key: 'name', title: 'Member', type: 'avatar', value: (r) => r.name, subtitle: (r) => r.email, width: 240 },
        { key: 'role', title: 'Role', type: 'select', value: (r) => r.role, options: ROLES, width: 120 },
        { key: 'status', title: 'Status', type: 'status', value: (r) => r.status, options: ['active', 'invited', 'paused'], width: 120 },
        { key: 'mfa', title: '2FA', type: 'boolean', value: (r) => r.mfa, width: 80, align: 'center' },
        { key: 'seen', title: 'Last active', type: 'date', value: (r) => r.seen, width: 150 },
      ]}
    />
  );
}
```

## Tree data

`getChildren` turns rows into a tree: children sit indented under their parent with a chevron. A search or filter keeps the parents of every match, opened, so a match never loses its place.

```tsx live full
import { DataGrid } from '@patine-ui/pro';

const team = (name, budget, spent, children) => ({ id: name, name, budget, spent, children });
const ORG = [
  team('Engineering', 4200000, 3610000, [
    team('Platform', 1600000, 1490000, [team('Infrastructure', 900000, 880000), team('Developer tools', 700000, 610000)]),
    team('Mobile', 1300000, 1020000, [team('iOS', 650000, 540000), team('Android', 650000, 480000)]),
    team('Web', 1300000, 1100000),
  ]),
  team('Design', 900000, 610000, [team('Product design', 600000, 420000), team('Brand', 300000, 190000)]),
  team('Go to market', 2600000, 2710000, [team('Sales', 1700000, 1810000), team('Marketing', 900000, 900000)]),
];

export default function Budget() {
  return (
    <DataGrid
      title="Budget by team"
      rows={ORG}
      rowKey={(r) => r.id}
      getChildren={(r) => r.children}
      accessibilityLabel="Budget by team"
      paging="scroll"
      height={420}
      columns={[
        { key: 'name', title: 'Team', value: (r) => r.name, width: 260 },
        { key: 'budget', title: 'Budget', type: 'currency', value: (r) => r.budget, width: 150 },
        { key: 'spent', title: 'Spent', type: 'currency', value: (r) => r.spent, width: 150 },
        { key: 'used', title: 'Used', type: 'progress', value: (r) => r.spent / r.budget, width: 180 },
        { key: 'left', title: 'Remaining', type: 'currency', value: (r) => r.budget - r.spent, width: 150 },
      ]}
    />
  );
}
```

## 10,000 rows

Rows are virtualized: only the ones in view are drawn, so the grid scrolls 10,000 rows as smoothly as 10. `paging="scroll"` drops the pager for one scrolling body under a sticky header, with the totals stuck to the foot. Sorting, searching and filtering run on every row in milliseconds.

```tsx live full
import { DataGrid } from '@patine-ui/pro';

const CITIES = ['Berlin', 'Lisbon', 'Austin', 'Osaka', 'Toronto', 'Nairobi', 'Seoul', 'Lima'];
const KINDS = ['Card', 'Transfer', 'Wallet', 'Refund'];
const EVENTS = Array.from({ length: 10000 }, (_, i) => ({
  id: `TX-${100000 + i}`,
  city: CITIES[(i * 7) % CITIES.length],
  kind: KINDS[(i * 13) % KINDS.length],
  amount: Math.round(((i * 7919) % 50000) / 3) / 10 + 1,
  fee: ((i * 31) % 300) / 10000,
  ok: i % 17 !== 0,
}));

export default function Transactions() {
  return (
    <DataGrid
      title="Transactions"
      rows={EVENTS}
      rowKey={(r) => r.id}
      accessibilityLabel="Transactions"
      paging="scroll"
      height={480}
      defaultDensity="compact"
      columns={[
        { key: 'id', title: 'ID', value: (r) => r.id, width: 130, pinned: true, aggregate: 'count' },
        { key: 'city', title: 'City', type: 'select', value: (r) => r.city, width: 130 },
        { key: 'kind', title: 'Method', type: 'select', value: (r) => r.kind, width: 130 },
        { key: 'amount', title: 'Amount', type: 'currency', value: (r) => r.amount, width: 140, aggregate: 'sum' },
        { key: 'fee', title: 'Fee', type: 'percent', value: (r) => r.fee, width: 100, aggregate: 'avg' },
        { key: 'ok', title: 'Settled', type: 'boolean', value: (r) => r.ok, width: 100, align: 'center' },
      ]}
    />
  );
}
```

## Server-side data

Pass `rowCount`, the total your server has, and the grid stops searching, sorting and paging itself. `onQueryChange` gets everything a server needs whenever it changes (the search after a short pause): `{ search, sort, filters, filter, quickFilter, groupBy, page, pageSize }`, with the filter row and the builder already as rules. Set `loading` while you fetch: skeleton rows the first time, a thin bar over the rows after that. `error` and `onRetry` cover a failed request.

```tsx live full
import { DataGrid, sortGrid, filterGrid } from '@patine-ui/pro';

const PLANS = ['Free', 'Pro', 'Team', 'Enterprise'];
const ACCOUNTS = Array.from({ length: 1204 }, (_, i) => ({
  id: `acct_${(9000 + i).toString(36)}`,
  name: `${['Blue', 'North', 'Bright', 'Pixel', 'Atlas', 'Cedar'][i % 6]} ${['Labs', 'Studio', 'Co', 'Systems', 'Works'][i % 5]} ${i + 1}`,
  plan: PLANS[(i * 7) % 4],
  mrr: ((i * 7919) % 900) + 20,
  seats: 1 + ((i * 13) % 80),
}));
const COLUMNS = [
  { key: 'name', title: 'Account', value: (r) => r.name, width: 220 },
  { key: 'plan', title: 'Plan', type: 'status', value: (r) => r.plan, options: PLANS, variants: { Free: 'secondary', Pro: 'default', Team: 'warning', Enterprise: 'success' }, width: 140 },
  { key: 'mrr', title: 'MRR', type: 'currency', value: (r) => r.mrr, width: 120 },
  { key: 'seats', title: 'Seats', type: 'number', value: (r) => r.seats, width: 100 },
];

// A pretend API: filters, sorts and pages on the "server", after 600 ms.
const fetchAccounts = (q) =>
  new Promise((resolve) =>
    setTimeout(() => {
      const matched = filterGrid(ACCOUNTS, { columns: COLUMNS, search: q.search, model: { logic: 'and', rules: q.filters } });
      const sorted = sortGrid(matched, q.sort, COLUMNS);
      resolve({ rows: sorted.slice((q.page - 1) * q.pageSize, q.page * q.pageSize), total: matched.length });
    }, 600)
  );

export default function Accounts() {
  const [data, setData] = useState({ rows: [], total: 0 });
  const [loading, setLoading] = useState(true);
  const latest = useRef(0);
  return (
    <DataGrid
      title="Accounts"
      rows={data.rows}
      rowCount={data.total}
      loading={loading}
      rowKey={(r) => r.id}
      accessibilityLabel="Accounts"
      pageSize={8}
      bulkActions={[{ label: 'Export', icon: 'download', onPress: (ids, { all }) => {} }]}
      onQueryChange={(q) => {
        const call = ++latest.current;
        setLoading(true);
        fetchAccounts(q).then((res) => {
          if (call !== latest.current) return; // a newer query won
          setData(res);
          setLoading(false);
        });
      }}
      columns={COLUMNS}
    />
  );
}
```

`sortGrid` and `filterGrid` are the grid's own sort and filter, exported for a mock server like this one or a Node backend. For a feed that loads as you scroll, use `paging="infinite"` with `onEndReached` and `hasMore`.

## Saved views

`views` are named sets of columns (order, widths, pins, what's hidden), sort, filters, grouping, quick filter and density. The views menu switches between them, marks the current one with a dot when you've changed something, and offers **Save changes**, **Save as new view** and **Delete**. Pass `onViewsChange` to store them (in your database or `localStorage`); without it they live as long as the grid. The contacts example at the top has two.

```tsx
<DataGrid
  views={views}
  onViewsChange={(next) => save('contacts.views', next)}
  defaultViewId="pipeline"
  {...props}
/>
```

## On phones

Under 640 points each row is a card: the first column as its title (with the avatar for a person), the first status as a badge, the next four columns as labelled lines, and a foot with its checkbox, **Show details** and the ⋯ menu. **Filters** opens a sheet with sort, group by and every filter as chips with counts, and a **Show 128 results** button that updates as you pick. Totals sit above the cards. Pass `renderCard` to design the card yourself.

## Accessibility

- The body is an ARIA `grid` with its row and column counts; rows say when they're ticked, headers how they're sorted, and the focused cell is the grid's active descendant, so screen readers follow the keyboard.
- Every control is labelled: sort buttons ("Shift-press to add to the sort"), header and row menus, checkboxes, chevrons, filters, pins, the pager. Counts and "1–10 of 1,204" are announced as they change.
- Status, ratings, booleans and progress are read as words and numbers, never color alone. A bad edit is announced as an alert with its reason.
- Row drag has Move up and Move down actions for screen readers. Touch targets are 44 points.

## Props

| Prop | Type | Default |
| --- | --- | --- |
| `rows` | `T[]` | |
| `columns` | `GridColumn<T>[]` (see [Columns](#columns)): `{ key, title, value, type?, render?, options?, variants?, currency?, max?, format?, href?, image?, subtitle?, series?, aggregate?, width?, minWidth?, align?, sortable?, filter?, pinned?, hidden?, editable?, validate?, groupable? }` | |
| `rowKey` | `(row) => string` | |
| `accessibilityLabel` | `string` | |
| `title` | `string`, beside the search | |
| `paging` | `'pages'` \| `'scroll'` \| `'infinite'` | `'pages'` |
| `pageSize` | `number` | `25` |
| `height` | `number`, the body's height while it scrolls | `560` |
| `initialSort` | `{ key, direction }` or a list | |
| `initialGroupBy` | `string[]` | |
| `quickFilters` | `{ key, label, match?(row), count? }[]` | |
| `views` | `{ id, name, state }[]` | |
| `defaultViewId` | `string` | None: every row |
| `onViewsChange` | `(views) => void` | |
| `bulkActions` | `{ label, icon?, destructive?, onPress(ids, { all }) }[]` | |
| `rowActions` | `(row) => { label, icon?, destructive?, disabled?, onPress(row) }[]` | |
| `renderExpanded` | `(row) => ReactNode`, a detail panel | |
| `getChildren` | `(row) => T[]`, tree data | |
| `onRowPress` | `(row) => void` | |
| `onCellChange` | `(row, key, value) => void` | |
| `onCellEdit` | `(row, key, text) => void`, kept for older code | |
| `onRowReorder` | `(id, toIndex) => void` | |
| `showTotals` | `boolean` | When a column has `aggregate` |
| `rowCount` | `number`: server mode | |
| `onQueryChange` | `(query: GridQuery) => void` | |
| `loading` | `boolean` | `false` |
| `onEndReached`, `hasMore` | Infinite paging | |
| `error`, `onRetry` | `string`, `() => void` | |
| `renderCard` | `(row) => ReactNode`, a row on phones | Title, badge and four lines |
| `onExport` | `(csv) => void` | Download or share |
| `exportName` | `string` | `'export.csv'` |
| `defaultDensity` | `'compact'` \| `'comfortable'` | the theme's `density` |
| `locale` | `string`, for money, numbers and dates | `'en-US'` |
| `emptyState` | `ReactNode` | |
| `labels` | `Partial<DataGridLabels>` | English |

Also exported: `sortGrid`, `filterGrid`, `applyRule`, `matchesModel`, `aggregate`, `formatCell`, `toCSV`, `paginate`, `filterRows`, and the types `GridColumn`, `GridQuery`, `GridView`, `FilterModel`, `FilterRule`, `ColumnType`.

## Related

- [Table](../components/table): static rows, free.
- [App layout](../pro/layout): `DataTable`, a lighter sortable table for Pro screens.
- [Sparkline](../components/sparkline): the trend in a `sparkline` column.
