# React

> Use Birch UI Grid in React and Next.js with the BirchGrid component, typed generics, a ref to the grid API and server rendering.

`@birchui/react` turns every Birch UI widget into a React component. `BirchGrid` accepts every [grid option](https://docs.birchui.com/api/core.md#gridoptions) as a prop, every [grid event](https://docs.birchui.com/grid/events.md) as an `on…` prop, and gives you the full `GridApi` through a ref. It supports React 18 and 19.

## Install

```bash
npm install @birchui/core @birchui/react
```

Add `@birchui/grid-pro` for Grid Pro features and `@birchui/scheduler` for the [scheduler component](https://docs.birchui.com/frameworks/scheduler.md).

## A complete example

```tsx title="OrdersGrid.tsx"
import { useMemo, useRef, useState } from 'react';
import { BirchGrid } from '@birchui/react';
import type { CellValueChangedEvent, ColumnDef, GridApi } from '@birchui/core';

export interface Order {
  id: string;
  customer: string;
  region: 'EMEA' | 'Americas' | 'APAC';
  placedAt: string;
  status: 'open' | 'shipped' | 'cancelled';
  total: number;
}

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 120, pinned: 'left' },
  { field: 'customer', header: 'Customer', flex: 1, filter: 'text', editable: true },
  { field: 'region', header: 'Region', filter: 'set' },
  { field: 'placedAt', header: 'Placed', type: 'date', filter: 'date' },
  {
    field: 'status',
    header: 'Status',
    editable: true,
    editor: 'select',
    options: ['open', 'shipped', 'cancelled'],
  },
  { field: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)) },
];

const getRowId = (order: Order) => order.id;

export function OrdersGrid({ orders }: { orders: Order[] }) {
  const grid = useRef<GridApi<Order>>(null);
  const [search, setSearch] = useState('');
  const [selectedCount, setSelectedCount] = useState(0);
  const pagination = useMemo(() => ({ pageSize: 50 }), []);

  async function saveChange({ row, colId, oldValue }: CellValueChangedEvent<Order>) {
    const response = await fetch(`/api/orders/${row.id}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(row),
    });
    if (!response.ok) grid.current?.setValue(row, colId, oldValue, 'api');
  }

  return (
    <section>
      <div className="toolbar">
        <input
          type="search"
          placeholder="Search orders"
          value={search}
          onChange={(event) => setSearch(event.target.value)}
        />
        <button type="button" onClick={() => grid.current?.downloadCsv({ fileName: 'orders.csv' })}>
          Export CSV
        </button>
        <span>{selectedCount} selected</span>
      </div>

      <BirchGrid<Order>
        ref={grid}
        className="orders-grid"
        style={{ height: 480 }}
        columns={columns}
        rows={orders}
        getRowId={getRowId}
        quickFilter={search}
        rowSelection="multiple"
        checkboxSelection
        pagination={pagination}
        onSelectionChanged={({ selected }) => setSelectedCount(selected.length)}
        onCellValueChanged={saveChange}
      />
    </section>
  );
}
```

`BirchGrid` renders a single `div` and creates the grid inside it. Give it a height with `style` or `className`; the grid fills that element and virtualizes everything inside.

## Props

Every key of [`GridOptions`](https://docs.birchui.com/api/core.md#gridoptions) is a prop with the same name and type: `columns`, `rows`, `getRowId`, `sort`, `filterModel`, `quickFilter`, `pagination`, `theme`, `density`, `modules`, `licenseKey` and the rest. Three more props go to the container element instead of the grid: `className`, `style` and `id`.

Events are props named `on` plus the capitalized event name:

| Grid event | Prop |
| --- | --- |
| `ready` | `onReady` |
| `cellClick`, `cellDoubleClick`, `cellKeyDown` | `onCellClick`, `onCellDoubleClick`, `onCellKeyDown` |
| `cellValueChanged` | `onCellValueChanged` |
| `rowClick` | `onRowClick` |
| `selectionChanged` | `onSelectionChanged` |
| `sortChanged`, `filterChanged` | `onSortChanged`, `onFilterChanged` |
| `columnResized`, `columnMoved`, `columnPinned`, `columnVisible`, `columnStateChanged` | `onColumnResized`, `onColumnMoved`, `onColumnPinned`, `onColumnVisible`, `onColumnStateChanged` |
| `modelUpdated`, `focusChanged`, `viewportScroll`, `pageChanged` | `onModelUpdated`, `onFocusChanged`, `onViewportScroll`, `onPageChanged` |
| `rowExpanded`, `editStart`, `editStop` | `onRowExpanded`, `onEditStart`, `onEditStop` |

Each handler receives the event payload object, typed for your row type. If a handler throws, the error is reported with `console.error` and the grid keeps working.

**`BirchGridProps`** (type from `@birchui/react`, full reference: https://docs.birchui.com/api/react.md)

```ts
type BirchGridProps<TRow = RowData> = BirchComponentProps<GridOptions<TRow>, GridEvents<TRow>> &
  RefAttributes<GridApi<TRow>>;
```

## Props and updates

The grid is created once, when the component mounts. On every later render the component compares each option prop with the value it last sent, using `Object.is`, and passes only the changed keys to `api.update()`. A prop that you remove is sent as `undefined`. The grid is never recreated.

This has two practical consequences:

- **Keep option values stable.** An inline array, object or function is a new value on every render, so it is sent to the grid every time. Define `columns`, `getRowId`, `pagination`, `modules` and similar values outside the component, or wrap them in `useMemo` and `useCallback`.
- **Replace, do not mutate.** Pushing into the `rows` array you already passed is not detected. Pass a new array, or use the ref and call `applyTransaction`.

Event handlers are different: the component always calls the handler from the latest render, and changing a handler never updates the grid. Inline arrow functions are fine for `on…` props.

```tsx
const modules = [RowGroupingModule, AggregationModule];

function RegionalSales({ rows }: { rows: Sale[] }) {
  const groupBy = useMemo(() => ['region', 'country'], []);
  return <BirchGrid<Sale> columns={salesColumns} rows={rows} modules={modules} groupBy={groupBy} />;
}
```

## Typed generics

`BirchGrid` is generic over your row type. Write the type argument explicitly, or let TypeScript infer it from `rows` and `columns`:

```tsx
<BirchGrid<Technician>
  columns={technicianColumns}
  rows={technicians}
  onRowClick={({ row }) => row && openTechnician(row.id)}
/>
```

With the type argument in place, `row` in every handler is a `Technician`, `columns` must be `ColumnDef<Technician>[]` and the ref must be a `GridApi<Technician>`. For wrapper components, use the exported props type:

```tsx title="DataTable.tsx"
import { BirchGrid, type BirchGridProps } from '@birchui/react';
import type { RowData } from '@birchui/core';

export function DataTable<TRow extends RowData>(props: BirchGridProps<TRow>) {
  return <BirchGrid<TRow> density="compact" stripes {...props} className="data-table" />;
}
```

## Using the grid API

The ref gives you the [`GridApi`](https://docs.birchui.com/api/core.md#gridapi). It is `null` until the component has mounted and again after it unmounts, so use it in event handlers and effects, not during render.

```tsx
const grid = useRef<GridApi<Order>>(null);

useEffect(() => {
  const socket = new WebSocket('wss://orders.example.com/stream');
  socket.onmessage = (message) => {
    const { added, changed, removedIds } = JSON.parse(message.data);
    grid.current?.applyTransaction({ add: added, update: changed, remove: removedIds });
  };
  return () => socket.close();
}, []);
```

You can also read the API from the `ready` event: `onReady={({ api }) => api.autosizeColumns()}`.

Common calls from React code:

```tsx
grid.current?.setSort([{ colId: 'total', dir: 'desc' }]);
grid.current?.setFilter('region', { type: 'set', values: ['EMEA'] });
grid.current?.scrollToRow(0, 'start');
const state = grid.current?.getColumnState();
```

## Controlled state

Some options double as state that users change, such as `sort`, `filterModel`, `quickFilter` and `pagination.page`. You can let the grid own that state and only listen to changes, or control it from React.

`sortChanged` and `filterChanged` fire for every change, including changes you make through props or `update()`, and each payload is a fresh copy. If you store the payload and pass it back as a prop, keep the current state when nothing actually changed. Otherwise every echo starts another round:

```tsx
import { useState } from 'react';
import { BirchGrid } from '@birchui/react';
import type { SortItem } from '@birchui/core';

const sameSort = (a: SortItem[], b: SortItem[]) =>
  a.length === b.length && a.every((item, index) => item.colId === b[index].colId && item.dir === b[index].dir);

function ControlledSort({ orders }: { orders: Order[] }) {
  const [sort, setSort] = useState<SortItem[]>([{ colId: 'placedAt', dir: 'desc' }]);
  return (
    <BirchGrid<Order>
      columns={columns}
      rows={orders}
      sort={sort}
      onSortChanged={({ sort: next }) => setSort((current) => (sameSort(current, next) ? current : next))}
    />
  );
}
```

Returning the current state lets React skip the render, so the round trip ends after one echo. If you only need to save the sort, for example in the URL or local storage, store it without passing it back as a prop.

### Saving column layout

```tsx
const storageKey = 'orders-grid-columns';

function PersistentOrdersGrid({ orders }: { orders: Order[] }) {
  const grid = useRef<GridApi<Order>>(null);
  return (
    <BirchGrid<Order>
      ref={grid}
      columns={columns}
      rows={orders}
      onReady={({ api }) => {
        const saved = localStorage.getItem(storageKey);
        if (saved) api.applyColumnState(JSON.parse(saved));
      }}
      onColumnStateChanged={({ state }) => localStorage.setItem(storageKey, JSON.stringify(state))}
    />
  );
}
```

## Grid Pro

Pass modules through the `modules` prop and set your key once:

```tsx title="main.tsx"
import { setLicenseKey } from '@birchui/license';

setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY);
```

```tsx title="RevenueByRegion.tsx"
import { BirchGrid } from '@birchui/react';
import { AllProModules } from '@birchui/grid-pro';
import type { ColumnDef } from '@birchui/core';

interface Sale {
  region: string;
  country: string;
  product: string;
  revenue: number;
}

const columns: ColumnDef<Sale>[] = [
  { field: 'region', header: 'Region', rowGroup: true },
  { field: 'country', header: 'Country', rowGroup: true },
  { field: 'product', header: 'Product' },
  { field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' },
];

export function RevenueByRegion({ sales }: { sales: Sale[] }) {
  return (
    <BirchGrid<Sale>
      style={{ height: 520 }}
      columns={columns}
      rows={sales}
      modules={AllProModules}
      groupDefaultExpanded={1}
      groupPanel
      statusBar
    />
  );
}
```

## Next.js and server rendering

`@birchui/react` is safe to import on the server. During server rendering, `BirchGrid` outputs its empty container `div`; the grid is created in the browser after hydration. The component uses a layout effect in the browser and a plain effect on the server, so React prints no warnings.

### App Router

`BirchGrid` uses refs and effects, so the component that renders it must be a Client Component. Put `'use client'` at the top of that file:

```tsx title="app/orders/orders-grid.tsx"
'use client';

import { BirchGrid } from '@birchui/react';
import type { ColumnDef } from '@birchui/core';
import type { Order } from './types';

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 120 },
  { field: 'customer', header: 'Customer', flex: 1 },
  { field: 'total', header: 'Total', type: 'number' },
];

export function OrdersGrid({ orders }: { orders: Order[] }) {
  return <BirchGrid<Order> style={{ height: 'calc(100vh - 160px)' }} columns={columns} rows={orders} />;
}
```

Fetch data in a Server Component and pass it down as a prop:

```tsx title="app/orders/page.tsx"
import { OrdersGrid } from './orders-grid';
import { listOrders } from '@/lib/orders';

export default async function OrdersPage() {
  const orders = await listOrders({ status: 'open' });
  return <OrdersGrid orders={orders} />;
}
```

> **Functions cannot cross the server boundary**
>
> Props passed from a Server Component to a Client Component must be serializable. Column definitions usually contain functions such as `format` or `valueGetter`, so define `columns` inside the Client Component file, as above, and pass only data from the server.

Set the license key in a Client Component that is part of your root layout, for example a small `providers.tsx` with `'use client'` that calls `setLicenseKey(process.env.NEXT_PUBLIC_BIRCHUI_LICENSE_KEY)` at module level.

### Pages Router, Remix and React Router

No special setup is needed. Render `BirchGrid` like any other component; it mounts in the browser.

### Strict Mode

In development, React Strict Mode mounts, unmounts and mounts components again. The grid is created, destroyed and created again, and the final instance is the one your ref points to. Nothing extra is needed.

## Wrapping your own widgets

`createReactComponent` turns any widget that follows the Birch UI widget contract (`create(container, options)` returning `update`, `on` and `destroy`) into a React component with the same prop, event and ref behaviour. `BirchGrid` and `BirchScheduler` are built this way, and you can use it for widgets of your own:

```tsx title="ShipmentMap.tsx"
import { defineWidget } from '@birchui/core';
import { createReactComponent } from '@birchui/react';
import {
  createShipmentMap,
  type ShipmentMapApi,
  type ShipmentMapEvents,
  type ShipmentMapOptions,
} from './shipment-map';

const shipmentMapDefinition = defineWidget<ShipmentMapOptions, ShipmentMapEvents, ShipmentMapApi>({
  name: 'ShipmentMap',
  tagName: 'shipment-map',
  create: createShipmentMap,
  events: ['shipmentClick'],
});

export const ShipmentMap = createReactComponent(shipmentMapDefinition);
```

`<ShipmentMap ref={mapRef} shipments={shipments} onShipmentClick={openShipment} />` then works like `BirchGrid`. See [`WidgetDefinition`](https://docs.birchui.com/api/core.md#widgetdefinition).

## Event Calendar

`@birchui/react` has no calendar entry point. The Event Calendar follows the same widget contract, so the adapter's generic factory wraps it in one line. See the [Event Calendar overview](https://docs.birchui.com/calendar/overview.md) for its options and events.

```tsx title="EventCalendar.tsx"
import { createReactComponent } from '@birchui/react';
import { calendarDefinition } from '@birchui/calendar';

export const EventCalendar = createReactComponent(calendarDefinition);
```

```tsx title="ClinicCalendar.tsx"
'use client';

import { useRef } from 'react';
import type { CalendarApi, CalendarEvent } from '@birchui/calendar';
import { EventCalendar } from './EventCalendar';

export function ClinicCalendar({ appointments }: { appointments: CalendarEvent[] }) {
  const calendar = useRef<CalendarApi>(null);
  return (
    <>
      <button type="button" onClick={() => calendar.current?.today()}>
        Today
      </button>
      <EventCalendar
        ref={calendar}
        style={{ height: 720 }}
        view="week"
        timeZone="Europe/London"
        slotMinutes={15}
        events={appointments}
        onEventClick={({ event }) => console.info('Open appointment', event.id)}
      />
    </>
  );
}
```

The wrapped component behaves like `BirchGrid`: options are props, events are `on…` props and the ref is the `CalendarApi`.

### Other Birch UI products

Gantt, Pivot Studio, Charts, the diagram editor, the spreadsheet, the form renderer and the Form Builder work the same way: pass `ganttDefinition` from `@birchui/gantt`, `pivotStudioDefinition` from `@birchui/pivot-studio`, `chartDefinition` from `@birchui/charts`, `diagramDefinition` from `@birchui/diagram`, `spreadsheetDefinition` from `@birchui/spreadsheet`, `formDefinition` from `@birchui/forms` or `formBuilderDefinition` from `@birchui/forms/builder` to `createReactComponent`. The [Gantt](https://docs.birchui.com/gantt/overview.md), [Pivot Studio](https://docs.birchui.com/pivot-studio/overview.md), [Charts](https://docs.birchui.com/charts/overview.md), [Diagram](https://docs.birchui.com/diagram/overview.md), [Spreadsheet](https://docs.birchui.com/spreadsheet/overview.md) and [Forms](https://docs.birchui.com/forms/overview.md) overviews have complete examples.

## Next steps

- [Columns](https://docs.birchui.com/grid/columns.md) and [editing](https://docs.birchui.com/grid/editing.md) for column options.
- [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md) for `BirchScheduler`.
- The [@birchui/react API reference](https://docs.birchui.com/api/react.md).
