Web Component
Use the <birchui-grid> custom element from @birchui/element with properties, attributes and DOM events, in plain HTML or any framework.
@birchui/element registers Birch UI widgets as custom elements. <birchui-grid> works in plain HTML pages, server-rendered templates, CMS pages and any framework that can render custom elements. It does not use Shadow DOM, so your CSS reaches every cell.
Install and register#
npm install @birchui/core @birchui/elementCall defineBirchGrid() once before the element is used:
import { defineBirchGrid } from '@birchui/element';
defineBirchGrid();defineBirchGrid(tagName = 'birchui-grid') registers the element and returns its constructor. Calling it again returns the existing registration. Pass another name to register the element under your own tag, for example defineBirchGrid('orders-grid').
On the server, where customElements does not exist, it does nothing and returns undefined, so the call is safe in shared code.
A complete example#
<style>
birchui-grid {
display: block;
height: 480px;
}
</style>
<label>
Search
<input id="search" type="search" placeholder="Search orders" />
</label>
<span id="selected-count">0 selected</span>
<birchui-grid id="orders" theme="light" density="normal"></birchui-grid>
<script type="module">
import { defineBirchGrid } from '@birchui/element';
defineBirchGrid();
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const grid = document.querySelector('#orders');
grid.getRowId = (order) => order.id;
grid.rowSelection = 'multiple';
grid.checkboxSelection = true;
grid.rows = [
{ id: 'SO-10421', customer: 'Northwind Traders', region: 'EMEA', total: 1840.5 },
{ id: 'SO-10422', customer: 'Contoso Ltd', region: 'Americas', total: 312 },
{ id: 'SO-10423', customer: 'Tailspin Toys', region: 'APAC', total: 96.4 },
];
grid.columns = [
{ 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: 'total', header: 'Total', type: 'number', format: (value) => usd.format(value) },
];
document.querySelector('#search').addEventListener('input', (event) => {
grid.setAttribute('quick-filter', event.target.value);
});
grid.addEventListener('selection-changed', (event) => {
document.querySelector('#selected-count').textContent = `${event.detail.selected.length} selected`;
});
grid.addEventListener('cell-value-changed', (event) => {
const { row, colId, newValue } = event.detail;
console.info(`Order ${row.id}: ${colId} is now ${newValue}`);
});
</script>Custom elements are inline by default. Give birchui-grid display: block and a height; the grid fills the element.
When the grid is created#
The element creates its grid when it is connected to the document and its columns property is set. Set the other properties first, in any order, and set columns last if you want the grid to start with everything in place. Properties set before defineBirchGrid() runs are picked up when the element upgrades.
To create the grid immediately, without columns, call grid.create(). It returns the grid API, or null if the element is not connected yet (the grid is then created on connection).
Properties#
Every grid option is available as a property with the same name: columns, rows, getRowId, rowHeight, headerHeight, floatingFilters, quickFilter, sort, multiSort, filterModel, rowSelection, checkboxSelection, pagination, theme, density, defaultColumn, modules, licenseKey, overscanRows, overscanColumns, rowClass, emptyMessage, injectStyles, locale, stripes and every Grid Pro option (groupBy, groupDefaultExpanded, groupPanel, groupColumn, groupTotals, treeData, getDataPath, getParentId, pivot, rangeSelection, fillHandle, clipboard, statusBar, masterDetail).
ariaLabel is not a property, because HTMLElement already defines one. Set it with set or options.
Each assignment sends only that option to the grid. Values are compared by identity, so assign a new array or object to change rows, columns or nested options.
Three more members cover everything else:
| Member | Description |
|---|---|
api |
The GridApi, or null before the grid exists and after it is destroyed |
set(key, value) |
Sets one option. undefined removes it |
options |
Reads all options as an object. Assigning replaces the whole set: keys you leave out are reset |
create() |
Creates the grid now, even without columns |
grid.set('ariaLabel', 'Open orders');
grid.set('sort', [{ colId: 'total', dir: 'desc' }]);
grid.options = { ...grid.options, density: 'compact', stripes: true };
grid.api?.applyTransaction({ add: [{ id: 'SO-10424', customer: 'Litware Inc', region: 'EMEA', total: 2210 }] });Attributes#
A few string and number options can be set as HTML attributes, which is convenient in server-rendered markup:
| Attribute | Option | Type |
|---|---|---|
theme |
theme |
string: light, dark or auto |
density |
density |
string: compact, normal or comfortable |
row-height |
rowHeight |
number |
header-height |
headerHeight |
number |
quick-filter |
quickFilter |
string |
license-key |
licenseKey |
string |
locale |
locale |
string |
Changing an attribute updates the grid. Removing it removes the option. Everything else, including columns and rows, is set as a property.
Events#
Every grid event is dispatched as a DOM CustomEvent on the element, with a kebab-case name and the payload in event.detail. Events bubble and cross shadow roots, so you can listen on an ancestor.
| Grid event | DOM event |
|---|---|
ready |
ready |
cellClick, cellDoubleClick, cellKeyDown |
cell-click, cell-double-click, cell-key-down |
cellValueChanged |
cell-value-changed |
rowClick, selectionChanged |
row-click, selection-changed |
sortChanged, filterChanged |
sort-changed, filter-changed |
columnResized, columnMoved, columnPinned, columnVisible, columnStateChanged |
column-resized, column-moved, column-pinned, column-visible, column-state-changed |
modelUpdated, focusChanged, viewportScroll, pageChanged |
model-updated, focus-changed, viewport-scroll, page-changed |
rowExpanded, editStart, editStop |
row-expanded, edit-start, edit-stop |
document.body.addEventListener('column-state-changed', (event) => {
if (event.target.id === 'orders') localStorage.setItem('orders-columns', JSON.stringify(event.detail.state));
});Moving and removing the element#
Moving the element to another place in the document keeps its grid, rows and state. When the element is removed and not re-inserted in the same task, the grid is destroyed and api becomes null. Inserting it again creates a fresh grid from the element's current options.
TypeScript#
@birchui/element adds birchui-grid to HTMLElementTagNameMap, so document.querySelector('birchui-grid') is typed. Cast to BirchGridElement<TRow> for your row type:
import { defineBirchGrid, type BirchGridElement } from '@birchui/element';
import type { ColumnDef } from '@birchui/core';
interface WorkOrder {
id: string;
site: string;
technician: string;
dueAt: string;
priority: 'low' | 'normal' | 'urgent';
}
defineBirchGrid();
const grid = document.querySelector('#work-orders') as BirchGridElement<WorkOrder>;
const columns: ColumnDef<WorkOrder>[] = [
{ field: 'id', header: 'Work order', width: 130 },
{ field: 'site', header: 'Site', flex: 1 },
{ field: 'technician', header: 'Technician', filter: 'set' },
{ field: 'dueAt', header: 'Due', type: 'date' },
{ field: 'priority', header: 'Priority', filter: 'set' },
];
grid.getRowId = (order) => order.id;
grid.columns = columns;
grid.addEventListener('row-click', (event) => {
if (event.detail.row) console.info('Open work order', event.detail.row.id);
});Grid Pro#
Set modules like any other property:
import { defineBirchGrid } from '@birchui/element';
import { AllProModules } from '@birchui/grid-pro';
import { setLicenseKey } from '@birchui/license';
setLicenseKey(import.meta.env.VITE_BIRCHUI_LICENSE_KEY);
defineBirchGrid();
const grid = document.querySelector('birchui-grid')!;
grid.modules = AllProModules;
grid.groupBy = ['region'];
grid.statusBar = true;
grid.columns = [
{ field: 'region', header: 'Region' },
{ field: 'customer', header: 'Customer', flex: 1 },
{ field: 'revenue', header: 'Revenue', type: 'number', aggFunc: 'sum' },
];The license-key attribute works too, for pages where the key is rendered by the server.
Without a bundler#
The packages are standard ES modules, so a page can load them with an import map. Copy the dist folders of @birchui/core and @birchui/element to your static files and map the package names:
<script type="importmap">
{
"imports": {
"@birchui/core": "/vendor/birchui/core/index.js",
"@birchui/element": "/vendor/birchui/element/index.js"
}
}
</script>
<script type="module">
import { defineBirchGrid } from '@birchui/element';
defineBirchGrid();
</script>Inside other frameworks#
The framework adapters are usually the better fit, but the element works anywhere:
- Angular: add
CUSTOM_ELEMENTS_SCHEMAto the component'sschemasand bind properties with[columns]="columns". Listen with(cell-value-changed)="onChange($event.detail)". - Vue: tell the compiler the tag is a custom element (
compilerOptions.isCustomElement = (tag) => tag.startsWith('birchui-')), then bind properties with.prop, for example:columns.prop="columns". - Svelte: Svelte sets known element properties directly, so
<birchui-grid {columns} {rows}>works.
Extending the element#
getBirchGridElement() returns the element class without registering it, so you can subclass it and register the subclass under your own tag:
import { getBirchGridElement } from '@birchui/element';
import { orderColumns } from './orders';
class OrdersGridElement extends getBirchGridElement() {
constructor() {
super();
this.columns = orderColumns;
this.getRowId = (order) => order.id;
this.density = 'compact';
}
}
customElements.define('orders-grid', OrdersGridElement);<orders-grid></orders-grid> now brings its own columns, so a page only has to set rows.
Custom elements for your own widgets#
createElementRegistration(definition, config) and createElementClass(definition, config) build custom elements for any widget that follows the Birch UI widget contract. config lists the option keys to expose as properties, the observed attributes with their types ('string', 'number' or 'boolean') and the options required before the widget is created.
Event Calendar#
@birchui/element has no calendar entry point. Register the Event Calendar as a custom element with createElementRegistration, choosing the options to expose as properties and attributes. See the Event Calendar overview for its options and events.
import { createElementRegistration } from '@birchui/element';
import { calendarDefinition } from '@birchui/calendar';
const calendarElement = createElementRegistration(calendarDefinition, {
optionKeys: ['events', 'view', 'date', 'timeZone'],
attributes: { view: 'string', 'time-zone': 'string', 'license-key': 'string' },
});
calendarElement.define();define() registers <birchui-calendar>. Without requiredOptions, the element creates its calendar as soon as it is connected and has any option. Events arrive as kebab-case CustomEvents such as event-click and event-drop.
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 createElementRegistration. The Gantt, Pivot Studio, Charts, Diagram, Spreadsheet and Forms overviews have complete examples.
Scheduler#
defineBirchScheduler() from @birchui/element/scheduler registers <birchui-scheduler>. See Using the Scheduler in your framework.
Next steps#
- Theming for the
--lq-*CSS variables. - The @birchui/element API reference.