# Svelte

> Use Birch UI Grid in Svelte 5 and SvelteKit with the BirchGrid component or the use:birchGrid action.

`@birchui/svelte` gives you two ways to use a Birch UI widget in Svelte 5:

- **`BirchGrid`**, a component that takes grid options as props, events as `on…` props and exposes the grid API with `bind:api`.
- **`birchGrid`**, an action you attach to any element with `use:birchGrid={params}`.

Both create the grid in the browser only, so they work in SvelteKit with server rendering.

The components ship as `.svelte` source files that your app compiles. They are exposed as named exports through the `svelte` export condition, which Vite and SvelteKit (`@sveltejs/vite-plugin-svelte`) use by default, so `import { BirchGrid } from '@birchui/svelte'` works without extra configuration.

## Install

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

## The BirchGrid component

```svelte title="OrdersGrid.svelte"
<script lang="ts">
  import { BirchGrid } from '@birchui/svelte';
  import type { CellValueChangedEvent, ColumnDef, GridApi } from '@birchui/core';

  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;

  let orders = $state.raw<Order[]>([
    { id: 'SO-10421', customer: 'Northwind Traders', region: 'EMEA', placedAt: '2026-11-02', total: 1840.5 },
    { id: 'SO-10422', customer: 'Contoso Ltd', region: 'Americas', placedAt: '2026-11-03', total: 312 },
    { id: 'SO-10423', customer: 'Tailspin Toys', region: 'APAC', placedAt: '2026-11-04', total: 96.4 },
  ]);

  let search = $state('');
  let selectedCount = $state(0);
  let api: GridApi<Order> | null = $state.raw(null);

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

<div class="toolbar">
  <input type="search" placeholder="Search orders" bind:value={search} />
  <button type="button" onclick={() => api?.downloadCsv({ fileName: 'orders.csv' })}>Export CSV</button>
  <span>{selectedCount} selected</span>
</div>

<BirchGrid
  bind:api
  class="orders-grid"
  {columns}
  rows={orders}
  {getRowId}
  quickFilter={search}
  rowSelection="multiple"
  checkboxSelection
  onSelectionChanged={({ selected }) => (selectedCount = selected.length)}
  onCellValueChanged={saveChange}
/>

<style>
  :global(.orders-grid) {
    height: 480px;
  }
</style>
```

The component renders one `div` and creates the grid inside it. Size it with the `class` or `style` prop. Because the `div` belongs to the component, target the class with `:global(...)` from a parent's `<style>` block.

### Props

- Every [grid option](https://docs.birchui.com/api/core.md#gridoptions) is a prop with the same name: `columns`, `rows`, `getRowId`, `sort`, `filterModel`, `quickFilter`, `pagination`, `theme`, `modules`, `licenseKey` and the rest.
- Every [grid event](https://docs.birchui.com/grid/events.md) is a prop named `on` plus the capitalized event name: `onCellClick`, `onCellValueChanged`, `onSelectionChanged`, `onSortChanged`, `onColumnStateChanged`, `onReady` and so on. Each handler receives the event payload object.
- `class` and `style` (a string) are applied to the container.
- `api` is bindable. With `bind:api`, your variable holds the [`GridApi`](https://docs.birchui.com/api/core.md#gridapi) while the grid exists and `null` before it is created and after it is destroyed. Declare that variable with `$state.raw`, as in the example.

## The birchGrid action

The action attaches a grid to an element you render yourself. Its parameter is the grid options plus two extra keys:

- `on`: an object of event handlers keyed by the grid event name, such as `{ cellValueChanged, selectionChanged }`.
- `onReady`: a function that receives the grid API as soon as the grid is created.

```svelte title="TechnicianRoster.svelte"
<script lang="ts">
  import { birchGrid } from '@birchui/svelte';
  import type { ColumnDef, GridApi } from '@birchui/core';

  interface Technician {
    id: string;
    name: string;
    depot: string;
    skills: string;
    openJobs: number;
  }

  let { technicians }: { technicians: Technician[] } = $props();

  let api: GridApi<Technician> | undefined;

  const columns: ColumnDef<Technician>[] = [
    { field: 'name', header: 'Technician', flex: 1 },
    { field: 'depot', header: 'Depot', filter: 'set' },
    { field: 'skills', header: 'Skills', flex: 1 },
    { field: 'openJobs', header: 'Open jobs', type: 'number', filter: 'number' },
  ];
</script>

<div
  class="roster"
  use:birchGrid={{
    columns,
    rows: technicians,
    getRowId: (technician: Technician) => technician.id,
    density: 'compact',
    onReady: (grid) => (api = grid),
    on: {
      rowClick: ({ row }) => row && console.info('Open technician', row.id),
    },
  }}
></div>

<button type="button" onclick={() => api?.autosizeColumns()}>Fit columns</button>

<style>
  .roster {
    height: 420px;
  }
</style>
```

Use the action when you want the container in your own markup and styles. Both forms accept options typed for your row type.

## Updates and reactivity

The grid is created once. Whenever the props or the action parameter change, the adapter compares each option with the value it last sent, by identity, and passes only the changed keys to `api.update()`. Event handlers are always read from the latest props and never cause an update.

- **Use `$state.raw` for rows and for the API.** `$state` turns every row into a deep proxy, which is slow for large datasets, and mutating it in place (`orders.push(order)`) keeps the same array, so the grid is not told. With `$state.raw`, assign a new array: `orders = [...orders, order]`.
- **Use transactions for frequent changes.** `api.applyTransaction({ add, update, remove })` updates individual rows without replacing the data set.
- **Keep columns and callbacks stable.** Declare `columns`, `getRowId` and `modules` in `<script>` rather than inline in the markup.

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

function markShipped(order: Order) {
  api?.applyTransaction({ update: [{ ...order, status: 'shipped' }] });
}
```

## Typing

`BirchGrid` is generic over your row type. Svelte has no syntax for passing a type argument in markup, so the row type is inferred from the props you pass: typed `columns` (`ColumnDef<Order>[]`) or `rows` (`Order[]`) are enough. Every other prop then follows that type. `getRowId` and column callbacks receive an `Order`, handler payloads such as `onCellValueChanged` carry `row: Order`, and `bind:api` expects a `GridApi<Order>`. `svelte-check` reports a mistyped field, as in any other typed component.

The `birchGrid` action accepts the same typed options.

For wrapper components, `BirchGridProps<TRow>` describes the component props and `BirchGridComponent` the component type.

## Grid Pro

```svelte title="RevenueByRegion.svelte"
<script lang="ts">
  import { BirchGrid } from '@birchui/svelte';
  import { AllProModules } from '@birchui/grid-pro';
  import type { ColumnDef } from '@birchui/core';

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

  let { sales }: { sales: Sale[] } = $props();

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

<BirchGrid
  style="height: 520px"
  {columns}
  rows={sales}
  modules={AllProModules}
  groupDefaultExpanded={1}
  groupPanel
  statusBar
/>
```

## SvelteKit

Both the component and the action create the grid only in the browser: the component in an effect, the action when the element mounts. During server rendering the component outputs its empty container. No `browser` checks or dynamic imports are needed.

Load data in a `load` function and pass it to the page:

```ts title="src/routes/orders/+page.server.ts"
import type { PageServerLoad } from './$types';
import { listOrders } from '$lib/server/orders';

export const load: PageServerLoad = async () => ({
  orders: await listOrders({ status: 'open' }),
});
```

```svelte title="src/routes/orders/+page.svelte"
<script lang="ts">
  import OrdersGrid from '$lib/OrdersGrid.svelte';

  let { data } = $props();
</script>

<OrdersGrid orders={data.orders} />
```

Set the license key once in the root layout:

```svelte title="src/routes/+layout.svelte"
<script lang="ts">
  import { setLicenseKey } from '@birchui/license';
  import { PUBLIC_BIRCHUI_LICENSE_KEY } from '$env/static/public';

  let { children } = $props();

  setLicenseKey(PUBLIC_BIRCHUI_LICENSE_KEY);
</script>

{@render children()}
```

## Wrapping your own widgets

`createSvelteAction(definition)` builds an action for any widget that follows the Birch UI widget contract, with the same `on` and `onReady` parameters. `toActionParams(definition, props)` converts component-style props (`onCellClick`) into action parameters (`on: { cellClick }`), which is how the `BirchGrid` component is built.

## Scheduler

`BirchScheduler` and the `birchScheduler` action come from `@birchui/svelte/scheduler`. See [Using the Scheduler in your framework](https://docs.birchui.com/frameworks/scheduler.md).

## Event Calendar

`@birchui/svelte` 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.

```svelte title="ClinicCalendar.svelte"
<script lang="ts">
  import { createSvelteAction } from '@birchui/svelte';
  import { calendarDefinition, type CalendarEvent } from '@birchui/calendar';

  let { appointments }: { appointments: CalendarEvent[] } = $props();

  const calendar = createSvelteAction(calendarDefinition);
</script>

<div
  class="clinic-calendar"
  use:calendar={{
    view: 'week',
    timeZone: 'Europe/London',
    events: appointments,
    on: { eventClick: ({ event }) => console.info('Open appointment', event.id) },
  }}
></div>

<style>
  .clinic-calendar {
    height: 720px;
  }
</style>
```

### 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 `createSvelteAction`. 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 [filtering](https://docs.birchui.com/grid/filtering.md).
- The [@birchui/svelte API reference](https://docs.birchui.com/api/svelte.md).
