# React Native Dashboard Grid (Pro)

> A customizable React Native dashboard for iOS, Android and the web, like Datadog, Grafana and Notion: widgets on a 12-column grid (6 on tablets, one on phones) that people drag, resize, remove with Undo and add from a gallery, with the others reflowing around them. Layouts per breakpoint, arrow-key moves on the web, long-press reorder on phones, widget chrome with period switch, refresh, full screen, loading, empty and error states. Part of Patine Pro, React Native core only.

# DashboardGrid Pro

`DashboardGrid` is a dashboard people arrange themselves. Widgets sit on a 12-column grid. In edit mode a widget drags with the others moving out of its way and springs into place, its corner resizes it in whole cells, ✕ removes it with Undo, and a gallery adds more in the first gap they fit. The grid measures its own width, so it shows 6 columns on tablets and one on phones, where a long press reorders. Each breakpoint keeps its own layout, and `onLayoutChange` gives them back for you to save.

`Widget` is the chrome inside each cell: a title, a period switch, a ⋯ menu with Refresh, Full screen, Duplicate and Remove, "Updated 3 min ago", and calm loading, empty and error states. It's part of Patine Pro and uses React Native core only.

```tsx
import { DashboardGrid, Widget } from '@patine-ui/pro';
```

```tsx live full
import { useState } from 'react';
import { View } from 'react-native';
import { BarChart, Button, DashboardGrid, DonutChart, NumberTicker, Text, Widget } from '@patine-ui/pro';

const LAYOUT = [
  { id: 'revenue', type: 'revenue', x: 0, y: 0, w: 4, h: 3 },
  { id: 'orders', type: 'orders', x: 4, y: 0, w: 4, h: 3 },
  { id: 'users', type: 'users', x: 8, y: 0, w: 4, h: 3 },
  { id: 'channels', type: 'channels', x: 0, y: 3, w: 7, h: 5 },
  { id: 'devices', type: 'devices', x: 7, y: 3, w: 5, h: 5 },
];

const TEMPLATES = [
  { type: 'revenue', title: 'Revenue', icon: 'dollar', category: 'Metrics', w: 4, h: 3 },
  { type: 'orders', title: 'Orders', icon: 'cart', category: 'Metrics', w: 4, h: 3 },
  { type: 'users', title: 'Active users', icon: 'users', category: 'Metrics', w: 4, h: 3 },
  { type: 'channels', title: 'Channels', description: 'Visitors by source', icon: 'barChart', category: 'Charts', w: 7, h: 5, minW: 4, minH: 4 },
  { type: 'devices', title: 'Devices', description: 'Desktop, mobile and tablet', icon: 'smartphone', category: 'Charts', w: 5, h: 5, minW: 4, minH: 4 },
];

const METRICS = {
  revenue: { value: 48210, format: (v) => `$${Math.round(v).toLocaleString('en-US')}`, note: '+12% vs last week' },
  orders: { value: 1284, note: '+4% vs last week' },
  users: { value: 9362, note: '−2% vs last week' },
};

const CHANNELS = [
  { channel: 'Organic', visitors: 3820 },
  { channel: 'Direct', visitors: 2410 },
  { channel: 'Social', visitors: 1290 },
  { channel: 'Email', visitors: 760 },
];

const DEVICES = [
  { device: 'Desktop', visitors: 5430 },
  { device: 'Mobile', visitors: 3370 },
  { device: 'Tablet', visitors: 560 },
];

const title = (item) => TEMPLATES.find((t) => t.type === item.type)?.title ?? item.id;

export default function Dashboard() {
  const [editing, setEditing] = useState(false);
  const [layout, setLayout] = useState(LAYOUT);

  const renderItem = (item) => {
    const metric = METRICS[item.type];
    if (metric) {
      return (
        <Widget title={title(item)} updatedAt={Date.now() - 180000}>
          <NumberTicker value={metric.value} format={metric.format} size="3xl" weight="semibold" />
          <Text size="sm" color="textSecondary">{metric.note}</Text>
        </Widget>
      );
    }
    if (item.type === 'channels') {
      return (
        <Widget title="Channels" subtitle="Visitors by source">
          {({ height }) => (
            <BarChart data={CHANNELS} xKey="channel" series={[{ key: 'visitors', label: 'Visitors' }]} horizontal height={Math.max(140, height)} accessibilityLabel="Visitors by channel" />
          )}
        </Widget>
      );
    }
    return (
      <Widget title="Devices">
        {({ height }) => (
          <DonutChart data={DEVICES} nameKey="device" valueKey="visitors" height={Math.max(140, height - 36)} centerLabel="Visitors" accessibilityLabel="Visitors by device" />
        )}
      </Widget>
    );
  };

  return (
    <View style={{ width: '100%', gap: 16 }}>
      <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
        <Button variant={editing ? 'default' : 'outline'} onPress={() => setEditing(!editing)}>
          {editing ? 'Done' : 'Edit dashboard'}
        </Button>
      </View>
      <DashboardGrid
        layout={layout}
        onLayoutChange={setLayout}
        editing={editing}
        onEditingChange={setEditing}
        templates={TEMPLATES}
        getItemLabel={title}
        renderItem={renderItem}
        accessibilityLabel="Store dashboard"
      />
    </View>
  );
}
```

Try it: press **Edit dashboard**, drag a widget onto another, pull a corner to resize, remove one and press **Undo**, or tab to a widget and use the arrow keys.

## Layouts and saving

`layout` is the widest breakpoint's arrangement, in cells: `{ id, x, y, w, h }`, the shape react-grid-layout uses. The narrower ones are worked out from it (widgets keep their order and stack), until someone arranges one by hand. `onLayoutChange` fires after every move, resize, add, duplicate, remove or undo with the widest layout, every hand-made one in `layouts`, and the current breakpoint. Save both and pass them back to restore the dashboard.

```tsx
const [saved, setSaved] = useStoredState('dashboard', { layout: DEFAULT_LAYOUT, layouts: {} });

<DashboardGrid
  layout={saved.layout}
  layouts={saved.layouts}
  onLayoutChange={(layout, layouts) => setSaved({ layout, layouts })}
  renderItem={renderItem}
/>;
```

For a grid that keeps its own state, pass `defaultLayout` instead. `minW`, `maxW`, `minH` and `maxH` bound a widget's size, and `static: true` pins it: it can't be dragged, resized or pushed, and the others flow around it.

`columns`, `breakpoints`, `rowHeight` and `gap` change the grid itself: by default 12, 6 and 1 columns, starting at 1024 and 640 points of the grid's own width, with 56-point rows.

## Adding widgets

Pass `templates` and edit mode shows an **Add widget** tile that opens a gallery, grouped by `category`. A pick goes in the first gap it fits, and its `type` becomes the new item's `type`, so `renderItem` knows what to draw. To open the gallery from your own header, control it with `galleryOpen` and `onGalleryOpenChange`. `onAdd` and `onRemove` tell you which widget came or went.

## Widget

`Widget` draws the card. Its `children` can be a function of the content's size, so a chart fills whatever space the cell has after a resize.

```tsx live
import { Widget, LineChart } from '@patine-ui/pro';

const DAYS = Array.from({ length: 14 }, (_, i) => ({ day: `Nov ${i + 3}`, visitors: 820 + Math.round(Math.sin(i / 2) * 160) + i * 18 }));

export default function Example() {
  const [period, setPeriod] = React.useState('14d');
  return (
    <Widget
      style={{ width: '100%', maxWidth: 520, height: 300 }}
      title="Visitors"
      subtitle="Unique, per day"
      period={{
        value: period,
        onValueChange: setPeriod,
        options: [
          { label: '7 days', value: '7d' },
          { label: '14 days', value: '14d' },
        ],
      }}
      onRefresh={() => {}}
      updatedAt={Date.now() - 120000}
    >
      {({ height }) => (
        <LineChart data={DAYS} xKey="day" series={[{ key: 'visitors', label: 'Visitors' }]} height={Math.max(120, height)} accessibilityLabel="Visitors per day" />
      )}
    </Widget>
  );
}
```

Inside a `DashboardGrid` the ⋯ menu adds Full screen, Duplicate and Remove by itself. `actions` puts your own items first, and `useDashboardItem()` gives custom widgets the same item, edit state and actions.

## Loading, empty and error

`loading` shows a skeleton (a chart's shape, or your `skeleton`), `empty` a calm "No data for this period", and `error` a message with **Try again** that calls `onRetry`. The widget keeps its title and size in every state, so the dashboard doesn't jump while data arrives.

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

export default function Example() {
  return (
    <View style={{ width: '100%', gap: 16 }}>
      <Widget style={{ height: 200 }} title="Revenue" loading />
      <Widget style={{ height: 200 }} title="Refunds" empty />
      <Widget style={{ height: 200 }} title="Signups" error="The signups service timed out." onRetry={() => {}} />
    </View>
  );
}
```

## Number ticker

`NumberTicker` counts to each new value in tabular digits, so a KPI that updates doesn't wobble. Screen readers hear only the final value, and it jumps straight there with reduce motion on.

```tsx
<NumberTicker value={visitors} format={(v) => Math.round(v).toLocaleString()} size="3xl" weight="semibold" />
```

## Designs

- **Patine**: soft cards with a hairline and a low shadow; the drop spot is a dashed outline.
- **iOS**: grouped panels on the surface color, no border, as iOS widgets.
- **Material**: Material 3 filled (tonal) cards and a soft drop spot.
- **Web**: bordered panels with a divided header, as Grafana and Datadog.

## Accessibility

- The grid is a list and each widget a group named by its title. In edit mode each widget is a button that says where it is and how big ("Revenue, column 1, row 1, 4 by 3").
- On the web, the focused widget moves with the arrow keys, resizes with Shift and the arrow keys, and Delete removes it.
- Screen readers get Move left, right, up and down, Wider, Narrower, Taller and Shorter as actions, so nothing needs a drag.
- Removing announces "Revenue removed" with an Undo button. Loading widgets are marked busy, and errors are alerts.
- Lifting, settling and the number ticker follow the OS reduce-motion setting. Touch targets are 44 points.

## Props

### DashboardGrid

| Prop | Type | Default |
| --- | --- | --- |
| `renderItem` | `(item, { editing, breakpoint, fullScreen }) => ReactNode` | |
| `layout`, `defaultLayout` | `GridItem[]`: `{ id, type?, x, y, w, h, minW?, maxW?, minH?, maxH?, static? }` | |
| `layouts`, `defaultLayouts` | `{ compact?, medium?, expanded? }` | Worked out from `layout` |
| `onLayoutChange` | `(layout, layouts, breakpoint) => void` | |
| `editing`, `defaultEditing`, `onEditingChange` | `boolean` | `false` |
| `templates` | `{ type, title, description?, icon?, category?, w, h, minW?, maxW?, minH?, maxH? }[]` | None: no gallery |
| `galleryOpen`, `onGalleryOpenChange` | `boolean` | |
| `onAdd` | `(item, template) => void` | |
| `onRemove` | `(item) => void` | |
| `getItemLabel` | `(item) => string` | Its template's title, or its id |
| `columns` | `{ compact?, medium?, expanded? }` | `1`, `6`, `12` |
| `breakpoints` | `{ medium?, expanded? }`, in points of the grid's width | `640`, `1024` |
| `rowHeight` | `number` | `56` |
| `gap` | `number` | The theme's `spacing.lg` |
| `rtl` | `boolean` | The app's direction |
| `labels` | `Partial<DashboardLabels>` | English |
| `accessibilityLabel` | `string` | `'Dashboard'` |

### Widget

| Prop | Type | Default |
| --- | --- | --- |
| `title` | `string` | |
| `subtitle` | `string` | |
| `icon` | `IconName` | |
| `period` | `{ value, options: { label, value }[], onValueChange }` | |
| `onRefresh` | `() => void`, adds Refresh to the menu | |
| `actions` | `{ label, icon?, onPress, destructive? }[]` | |
| `loading`, `skeleton` | `boolean`, `ReactNode` | A chart's shape |
| `error`, `onRetry` | `string \| boolean`, `() => void` | |
| `empty`, `emptyTitle`, `emptyDescription` | `boolean`, `string` | "No data for this period" |
| `updatedAt`, `now` | `Date \| string \| number`, `Date` | |
| `headerRight`, `footer` | `ReactNode` | |
| `padded` | `boolean` | `true` |
| `children` | `ReactNode` or `({ width, height }) => ReactNode` | |

Also exported: `NumberTicker`, `useNumberTicker`, `useDashboardItem`, the layout helpers `addItem`, `removeItem`, `moveItem`, `resizeItem`, `compactLayout`, `deriveLayout`, `layoutFor`, `breakpointFor`, the constants `GRID_COLUMNS`, `GRID_BREAKPOINTS`, `DASHBOARD_LABELS`, and the types `GridItem`, `GridLayouts`, `GridBreakpoint`, `WidgetTemplate`, `WidgetProps`.

## Related

- [Analytics dashboard](../pro/analytics): a whole analytics screen built on this grid.
- [Stats row](./stats-row): a fixed row of KPIs.
- [Data grid](./data-grid): the table for a widget's details.
