Birch UI v0.1
Pricing

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.

Open .md

@birchui/react turns every Birch UI widget into a React component. BirchGrid accepts every grid option as a prop, every grid event as an on… prop, and gives you the full GridApi through a ref. It supports React 18 and 19.

Install#

Terminal
npm install @birchui/core @birchui/react

Add @birchui/grid-pro for Grid Pro features and @birchui/scheduler for the scheduler component.

A complete example#

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 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.

BirchGridPropstype@birchui/reactFull reference
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:

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. 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:

main.tsx
import { setLicenseKey } from '@birchui/license';

setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY);
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:

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:

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} />;
}

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:

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.

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 for its options and events.

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

export const EventCalendar = createReactComponent(calendarDefinition);
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, Pivot Studio, Charts, Diagram, Spreadsheet and Forms overviews have complete examples.

Next steps#

↑ ↓ to move, Enter to open, Esc to close