# Columns

> Define what each column shows and how it behaves with ColumnDef, from field paths and types to value getters, formatters and cell renderers.

Columns are described by an array of `ColumnDef` objects passed as `columns`. A column definition says where a value comes from, how it is compared, filtered and edited, and how it is displayed. Only one of `field` or `id` is required; every other property has a sensible default.

```ts title="invoice-columns.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

interface Invoice {
  number: string;
  customer: { name: string; country: string };
  issued: string;
  due: string;
  amount: number;
  paid: boolean;
}

const columns: ColumnDef<Invoice>[] = [
  { field: 'number', header: 'Invoice', width: 130, pinned: 'left' },
  { field: 'customer.name', header: 'Customer', flex: 2, minWidth: 200 },
  { field: 'customer.country', header: 'Country', width: 120, filter: true },
  { field: 'issued', type: 'date', width: 130 },
  { field: 'due', type: 'date', width: 130 },
  { field: 'amount', type: 'number', width: 140, format: (v) => `€${Number(v).toLocaleString('de-DE', { minimumFractionDigits: 2 })}` },
  { field: 'paid', type: 'boolean', width: 90 },
];

createGrid<Invoice>(document.querySelector('#invoices')!, { columns, rows: invoices, getRowId: (i) => i.number });
```

## Column IDs and headers

Every column has an ID used by the API, sort and filter models, column state and events. It is resolved in this order:

1. `id`, when set.
2. `field`, when set.
3. `col<index>`, the position in the `columns` array.

If two columns resolve to the same ID, the later one gets a suffix, so set an explicit `id` whenever you show the same field twice. IDs starting with two underscores are reserved for columns the grid generates, such as the selection checkbox column `__select`.

When `header` is omitted, the grid derives a label from the ID: it takes the last segment of a dotted path, turns underscores and hyphens into spaces, splits camelCase words and capitalizes the first letter. `orderDate` becomes "Order Date" and `customer.country` becomes "Country". `headerTooltip` sets the native tooltip on the header cell.

```ts
const columns: ColumnDef<Invoice>[] = [
  { field: 'amount', header: 'Net amount', headerTooltip: 'Excluding VAT' },
  { id: 'amountGross', field: 'amount', header: 'Gross amount', valueGetter: (row) => row.amount * 1.19 },
];
```

## Fields and nested paths

`field` is a property name or a dotted path into the row. `customer.name` reads `row.customer.name` and returns `undefined` if any segment is missing, so incomplete rows never throw. When a cell with a nested `field` is edited, the grid writes back along the same path and creates missing intermediate objects.

## Column types

`type` controls default comparison, filtering, editing, alignment and formatting. It defaults to `'text'`.

| Type | Sorting | Default format | Default editor | Default alignment | Filter when `filter: true` |
| --- | --- | --- | --- | --- | --- |
| `text` | Locale-aware, case-insensitive, numeric-aware ("Order 2" before "Order 10") | `String(value)` | Text input | Left | `text` |
| `number` | Numeric | `Intl.NumberFormat` with up to 2 fraction digits | Text input with a decimal keypad | Right | `number` |
| `date` | Chronological | `Intl.DateTimeFormat` with year, short month and day ("Mar 4, 2026") | Native date input | Left | `date` |
| `boolean` | `false` before `true` | "Yes" or "No" | Checkbox | Center | `boolean` |

Date columns accept `Date` objects, epoch milliseconds and ISO strings. A plain `YYYY-MM-DD` string is read as local midnight, so a due date of `2026-04-30` never shifts to the previous day in western time zones. Number columns accept numbers and numeric strings, including thousands separators such as `"12,500"`.

Formatting uses the grid's `locale` option, which defaults to the browser locale:

```ts
createGrid(container, { columns, rows, locale: 'de-DE' });
```

Blank values (`null`, `undefined`, an empty string or `NaN`) render as an empty cell and always sort last.

## Width, flex and limits

| Property | Default | Meaning |
| --- | --- | --- |
| `width` | `150` | Width in pixels. |
| `minWidth` | `40` | Lower bound for resizing, flex and autosize. |
| `maxWidth` | none | Upper bound for resizing, flex and autosize. |
| `flex` | none | Share of the remaining horizontal space. |

Columns with `flex` divide the space left over after fixed-width columns in proportion to their flex values, clamped by `minWidth` and `maxWidth`. A flex column that the user resizes keeps the width they chose and stops flexing.

```ts
const columns: ColumnDef<Invoice>[] = [
  { field: 'number', width: 120 },
  { field: 'customer.name', flex: 2, minWidth: 180 },
  { field: 'customer.country', flex: 1, maxWidth: 220 },
  { field: 'amount', type: 'number', width: 140 },
];
```

## Behaviour flags

| Property | Default | Meaning |
| --- | --- | --- |
| `sortable` | `true` | Header click sorts. See [Sorting](https://docs.birchui.com/grid/sorting.md). |
| `resizable` | `true` | The header edge can be dragged. See [Column operations](https://docs.birchui.com/grid/column-operations.md). |
| `reorderable` | `true` | The header can be dragged to a new position. |
| `filter` | `false` | `true` picks a filter from the column type, or name one: `'text'`, `'number'`, `'date'`, `'set'`, `'boolean'`. See [Filtering](https://docs.birchui.com/grid/filtering.md). |
| `editable` | `false` | `true` or a function of the cell context. See [Editing](https://docs.birchui.com/grid/editing.md). |
| `pinned` | `null` | `'left'` or `'right'` keeps the column in view while scrolling horizontally. |
| `hidden` | `false` | Hides the column without removing it. |

When `filter: true` is set and the column has `options`, the grid uses a set filter.

## Reading values: valueGetter

By default a cell's value is `row[field]`. A `valueGetter` computes it instead. Its result is what the grid sorts, filters, exports and passes to `format` and `cell`.

```ts
interface OrderLine {
  sku: string;
  quantity: number;
  unitPrice: number;
  discountRate: number;
}

const columns: ColumnDef<OrderLine>[] = [
  { field: 'sku', header: 'SKU' },
  { field: 'quantity', type: 'number' },
  { field: 'unitPrice', header: 'Unit price', type: 'number' },
  {
    id: 'lineTotal',
    header: 'Line total',
    type: 'number',
    valueGetter: (line) => line.quantity * line.unitPrice * (1 - line.discountRate),
  },
];
```

Value getters run often: on every render of a visible cell and for every row while sorting or filtering. Keep them cheap and pure. If a getter throws, the grid reports it with `console.error` and treats the value as `undefined`. See [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md#keep-value-getters-cheap) for large datasets.

## Writing values: valueSetter

When an editable cell commits, the grid writes the new value to `row[field]`. Columns that use a `valueGetter` need a `valueSetter` to be editable in a meaningful way:

```ts
const fullName: ColumnDef<{ firstName: string; lastName: string }> = {
  id: 'name',
  header: 'Technician',
  editable: true,
  valueGetter: (t) => `${t.firstName} ${t.lastName}`,
  valueSetter: (t, value) => {
    const [first, ...rest] = String(value).trim().split(/\s+/);
    t.firstName = first ?? '';
    t.lastName = rest.join(' ');
  },
};
```

## Formatting: format

`format(value, row)` returns the display string. It replaces the type's default formatter and is also used by the quick filter and by CSV export when `formatted: true`. `row` is `undefined` for rows that do not carry data, such as group rows in Grid Pro.

```ts
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const shortDate = new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: 'short' });

const columns: ColumnDef<Order>[] = [
  { field: 'revenue', type: 'number', format: (v) => (v == null ? '' : usd.format(Number(v))) },
  { field: 'orderDate', type: 'date', format: (v) => shortDate.format(new Date(String(v))) },
  { field: 'quantity', type: 'number', format: (v, row) => `${v} ${row?.unit ?? 'pcs'}` },
];
```

Sorting and filtering always use the raw value, never the formatted string, so a currency column still sorts numerically.

## Cell renderers: cell

`cell(ctx)` takes over the cell's content. Return a string (inserted as text, never as HTML), a DOM `Node`, `null` for an empty cell, or nothing (`undefined`) to keep the formatted value. If the renderer throws, the grid reports the error with `console.error` and shows the formatted value. The context gives you the raw `value`, the `formatted` string, the `row`, the `column`, the `rowIndex` and the `api`.

```ts
import type { CellContext, ColumnDef } from '@birchui/core';

const statusColors: Record<string, string> = {
  Shipped: '#1a7f37',
  Pending: '#9a6700',
  Backordered: '#cf222e',
  Cancelled: '#656d76',
};

function statusBadge(ctx: CellContext<Order>): Node {
  const badge = document.createElement('span');
  badge.className = 'status-badge';
  badge.textContent = ctx.formatted;
  badge.style.color = statusColors[String(ctx.value)] ?? 'inherit';
  return badge;
}

const columns: ColumnDef<Order>[] = [
  { field: 'status', cell: statusBadge },
  {
    id: 'actions',
    header: '',
    width: 110,
    sortable: false,
    cell: (ctx) => {
      const button = document.createElement('button');
      button.type = 'button';
      button.textContent = 'Open';
      button.addEventListener('click', () => openOrder(ctx.row!.id));
      return button;
    },
  },
];
```

> **Tip**
>
> Cells are recycled while scrolling. Build the node from `ctx` every time and avoid holding references to rendered cells. For heavy content, keep the renderer small and see [Virtualization & performance](https://docs.birchui.com/grid/virtualization.md).

## Styling cells: cellClass, headerClass and align

`cellClass` adds classes to the cell element: a fixed string or a function of the cell context. `headerClass` adds classes to the header cell. `align` overrides the type's default alignment.

```ts
const columns: ColumnDef<Invoice>[] = [
  {
    field: 'due',
    type: 'date',
    cellClass: (ctx) => (!ctx.row?.paid && new Date(String(ctx.value)) < new Date() ? 'invoice-overdue' : undefined),
  },
  { field: 'amount', type: 'number', headerClass: 'header-emphasis', align: 'right' },
  { field: 'number', align: 'center' },
];
```

```css title="invoices.css"
.lq-grid .invoice-overdue {
  color: #cf222e;
  font-weight: 600;
}
.lq-grid .header-emphasis {
  font-weight: 700;
}
```

## Shared defaults: defaultColumn

`defaultColumn` is merged under every column definition. Properties set on a column always win.

```ts
createGrid(container, {
  defaultColumn: { filter: true, minWidth: 100, resizable: true },
  columns: [
    { field: 'customer', flex: 1 },
    { field: 'region' },
    { field: 'revenue', type: 'number', filter: 'number' },
    { id: 'actions', filter: false, sortable: false, cell: renderActions },
  ],
  rows: orders,
});
```

## Your own data: meta

`meta` is a free-form object the grid never reads. Use it for anything your renderers, modules or toolbars need, such as a unit, a permission or an analytics label.

```ts
const columns: ColumnDef<Order>[] = [
  { field: 'revenue', type: 'number', meta: { unit: 'USD', sensitive: true } },
];

const sensitiveIds = grid.getColumns().filter((c) => c.def.meta?.sensitive).map((c) => c.id);
```

## Resolved columns

The grid turns each `ColumnDef` into a `ResolvedColumn` with every default filled in. `getColumns()` returns them in display order, `getDisplayColumns()` only the visible ones (left-pinned, then unpinned, then right-pinned), and `getColumn(colId)` one by ID. The original definition is always available as `column.def`.

```ts
const revenue = grid.getColumn('revenue');
console.info(revenue?.width, revenue?.align, revenue?.filter);
```

**`ResolvedColumn`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ResolvedColumn<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `def` | `ColumnDef<TRow>` |  |
| `header` | `string` |  |
| `type` | `ColumnType` |  |
| `width` | `number` |  |
| `minWidth` | `number` |  |
| `maxWidth` | `number` |  |
| `pinned` | `'left' \| 'right' \| null` |  |
| `hidden` | `boolean` |  |
| `sortable` | `boolean` |  |
| `resizable` | `boolean` |  |
| `reorderable` | `boolean` |  |
| `rowHeader` | `boolean` |  |
| `filter` | `FilterKind \| null` |  |
| `align` | `'left' \| 'center' \| 'right'` |  |
| `generated` | `boolean` |  |

## Grid Pro column properties

> **Grid Pro: Paid feature. Fully functional without a key; a license removes the watermark. Pricing: https://docs.birchui.com/getting-started/pricing.md**
>
> `aggFunc`, `rowGroup`, `rowGroupIndex`, `pivot` and `pivotIndex` are read by Grid Pro modules. Without those modules installed they have no effect. See [Row grouping](https://docs.birchui.com/grid-pro/row-grouping.md), [Aggregation](https://docs.birchui.com/grid-pro/aggregation.md) and [Pivoting](https://docs.birchui.com/grid-pro/pivoting.md).

## ColumnDef reference

**`ColumnDef`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ColumnDef<TRow = RowData>
```

| Property | Type | Description |
| --- | --- | --- |
| `id?` | `string` |  |
| `field?` | `string` |  |
| `header?` | `string` |  |
| `headerTooltip?` | `string` |  |
| `type?` | `ColumnType` |  |
| `width?` | `number` |  |
| `minWidth?` | `number` |  |
| `maxWidth?` | `number` |  |
| `flex?` | `number` |  |
| `pinned?` | `'left' \| 'right' \| null` |  |
| `hidden?` | `boolean` |  |
| `sortable?` | `boolean` |  |
| `resizable?` | `boolean` |  |
| `reorderable?` | `boolean` |  |
| `rowHeader?` | `boolean` |  |
| `filter?` | `boolean \| FilterKind` |  |
| `editable?` | `boolean \| ((ctx: CellContext<TRow>) => boolean)` |  |
| `editor?` | `EditorKind \| CellEditorFactory<TRow>` |  |
| `options?` | `readonly SelectOption[]` |  |
| `valueGetter?` | `(row: TRow) => unknown` |  |
| `valueSetter?` | `(row: TRow, value: unknown) => void` |  |
| `valueParser?` | `(input: string, row: TRow) => unknown` |  |
| `format?` | `(value: unknown, row: TRow \| undefined) => string` |  |
| `cell?` | `(ctx: CellContext<TRow>) => string \| Node \| null \| void` |  |
| `cellClass?` | `string \| ((ctx: CellContext<TRow>) => string \| undefined)` |  |
| `headerClass?` | `string` |  |
| `align?` | `'left' \| 'center' \| 'right'` |  |
| `comparator?` | `(a: unknown, b: unknown, rowA: TRow, rowB: TRow) => number` |  |
| `aggFunc?` | `AggFuncName \| AggFunc` |  |
| `rowGroup?` | `boolean` |  |
| `rowGroupIndex?` | `number` |  |
| `pivot?` | `boolean` |  |
| `pivotIndex?` | `number` |  |
| `meta?` | `Record<string, unknown>` |  |
| `columnGroupShow?` | `'open' \| 'closed'` |  |
| `autoHeight?` | `boolean` |  |
| `wrapText?` | `boolean` |  |
| `rowDrag?` | `boolean` |  |

## Changing columns at runtime

Replace the full column list with `setColumns()` or `update({ columns })`. Widths, pinning, visibility and order that the user changed are kept for columns whose ID survives. See [Updating data](https://docs.birchui.com/grid/updating-data.md#changing-columns).
