# Solid

> Use Birch UI Grid in Solid and SolidStart with the generic BirchGrid component, reactive props and a ref to the grid API.

`@birchui/solid` wraps every Birch UI widget as a Solid component. `BirchGrid` is generic over your row type, takes every grid option as a reactive prop and every grid event as an `on…` prop, and hands you the grid API through `ref`. It supports Solid 1.8 and later.

## Install

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

## A complete example

```tsx title="OrdersGrid.tsx"
import { createSignal } from 'solid-js';
import { BirchGrid } from '@birchui/solid';
import type { CellValueChangedEvent, ColumnDef, GridApi } from '@birchui/core';

export interface Order {
  id: string;
  customer: string;
  region: 'EMEA' | 'Americas' | 'APAC';
  placedAt: string;
  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: 'total', header: 'Total', type: 'number', format: (value) => usd.format(Number(value)) },
];

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

export function OrdersGrid(props: { orders: Order[] }) {
  let grid: GridApi<Order> | undefined;
  const [search, setSearch] = createSignal('');
  const [selectedCount, setSelectedCount] = createSignal(0);

  function saveChange({ row, colId, newValue }: CellValueChangedEvent<Order>) {
    console.info(`Order ${row.id}: ${colId} is now ${String(newValue)}`);
  }

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

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

`BirchGrid` renders one `div` and creates the grid inside it on mount. Size it with `class` or `style`.

## Props

- Every [grid option](https://docs.birchui.com/api/core.md#gridoptions) is a prop with the same name and type.
- Every [grid event](https://docs.birchui.com/grid/events.md) is a prop named `on` plus the capitalized event name, for example `onCellClick`, `onCellValueChanged`, `onSortChanged`, `onColumnStateChanged` and `onReady`.
- `class`, `style` (an object or a string) and `id` are applied to the container.
- `ref` receives the [`GridApi`](https://docs.birchui.com/api/core.md#gridapi) once the grid is created.

## Reactive updates

Option props are tracked like any other Solid props. When a signal you pass changes, the component compares each option with the value it last sent, by identity, and calls `api.update()` with only the changed keys. The grid is never recreated. Event handlers are read when the event fires, so swapping a handler never touches the grid.

- **Pass new arrays.** Updating a store or signal so that `rows` is the same array mutated in place is not detected. Produce a new array, or call `grid.applyTransaction(...)`.
- **Avoid stores for large row sets.** A Solid store wraps each row in a proxy. For thousands of rows, keep data in a signal holding a plain array and update it immutably, or use transactions.
- **Keep columns and callbacks stable.** Define them outside the component or once at the top of it.

```tsx
const [orders, setOrders] = createSignal<Order[]>([]);

async function loadOrders() {
  const response = await fetch('/api/orders?status=open');
  setOrders(await response.json());
}

function addOrder(order: Order) {
  setOrders((current) => [...current, order]);
}
```

## The grid API

Pass a callback to `ref` to receive the API. In Solid, `ref={grid}` with a `let grid` variable compiles to the same callback:

```tsx
export function LargestOrders(props: { orders: Order[] }) {
  let grid: GridApi<Order> | undefined;

  function showBiggestFirst() {
    grid?.setSort([{ colId: 'total', dir: 'desc' }]);
    grid?.scrollToRow(0, 'start');
  }

  return (
    <>
      <button type="button" onClick={showBiggestFirst}>
        Largest first
      </button>
      <BirchGrid<Order> ref={grid} style={{ height: '420px' }} columns={columns} rows={props.orders} />
    </>
  );
}
```

The `onReady` prop also receives the API: `onReady={({ api }) => api.autosizeColumns()}`.

## Grid Pro

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

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

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

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

Set the license key once in your entry file with `setLicenseKey` from `@birchui/license`. See [Licensing and activation](https://docs.birchui.com/getting-started/licensing.md).

## SolidStart and server rendering

On the server, `BirchGrid` renders its empty container `div` with your `class`, `style` and `id`. The grid is created in `onMount`, which only runs in the browser, so no `clientOnly` wrapper is required. Give the container a height so the layout is stable when the grid appears.

## Wrapping your own widgets

`createSolidComponent(definition)` turns any widget that follows the Birch UI widget contract into a Solid component with the same props, events and `ref` behaviour. `BirchGrid` and `BirchScheduler` are built with it.

## Scheduler

`BirchScheduler` comes from `@birchui/solid/scheduler`. See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md).

## Event Calendar

`@birchui/solid` 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="ClinicCalendar.tsx"
import { createSolidComponent } from '@birchui/solid';
import { calendarDefinition, type CalendarEvent } from '@birchui/calendar';

const EventCalendar = createSolidComponent(calendarDefinition);

export function ClinicCalendar(props: { appointments: CalendarEvent[] }) {
  return (
    <EventCalendar
      style={{ height: '720px' }}
      view="week"
      timeZone="Europe/London"
      events={props.appointments}
      onEventClick={({ event }) => console.info('Open appointment', event.id)}
    />
  );
}
```

### 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 `createSolidComponent`. 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

- [Updating data](https://docs.birchui.com/grid/updating-data.md) and [selection](https://docs.birchui.com/grid/selection.md).
- The [@birchui/solid API reference](https://docs.birchui.com/api/solid.md).
