# Forms overview

> Render accessible, multi-page forms from a JSON schema with conditional logic, computed values, repeatable sections and validation, free under the MIT license.

Birch UI Forms turns a JSON schema into a complete, accessible form: labels, help text, validation messages, conditional questions, calculated totals, repeatable sections and multi-page navigation. You describe the form as data, so it can be stored in a database, edited in the [Form Builder](https://docs.birchui.com/forms/builder.md) or generated on a server, and the same schema renders identically in every framework.

The package has two parts:

| Part | Import | License |
| --- | --- | --- |
| Form renderer, schema engine, expressions, validation, JSON Schema converters, i18n | `@birchui/forms` | MIT, free for any use |
| Visual Form Builder | `@birchui/forms/builder` | Commercial, one-time purchase per developer |

**Live demo: Service request form** (runs on the HTML version of this page). Source of `demos/form-renderer.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createForm } from '@birchui/forms';
import { docsTheme, layout, onDocsThemeChange } from './_shared';
import { serviceRequest } from './_forms-data';

export const meta = { title: 'Service request form', height: 600 };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  body.style.overflow = 'auto';
  body.style.padding = '16px';
  toolbar.append('Choose "Emergency" to reveal a conditional field. Add units on the second page.');

  const form = createForm(body, {
    schema: serviceRequest,
    data: { company: 'Kestrel Logistics', region: 'Europe' },
    theme: docsTheme(),
  });

  const offs = [
    form.on('valueChange', ({ name, value }) => {
      status.textContent = `${name} = ${JSON.stringify(value)}`;
    }),
    form.on('validate', ({ valid, errors }) => {
      status.textContent = valid
        ? 'All fields are valid.'
        : `${errors.length} field(s) need attention: ${errors.map((e) => e.label).join(', ')}`;
    }),
    form.on('formSubmit', ({ data }) => {
      status.textContent = `Submitted: ${JSON.stringify(data)}`;
    }),
  ];
  status.textContent = 'Values appear here as you type.';
  const stopTheme = onDocsThemeChange((theme) => form.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    form.destroy();
  };
}
```

## Install

```bash
npm install @birchui/forms
```

Styles are injected automatically when a form is created. To load them as a stylesheet instead, pass `injectStyles: false` and import `@birchui/forms/styles.css`. Importing the package has no side effects and never touches `window`, so it is safe in server-rendered code.

## A first form

```ts title="service-request.ts"
import { createForm, type FormSchema } from '@birchui/forms';

const serviceRequest: FormSchema = {
  title: 'Equipment service request',
  description: 'Northgate Facilities. We respond to urgent requests within four hours.',
  completedMessage: 'Thank you. Your request has been logged and a technician will contact you.',
  elements: [
    { type: 'text', name: 'contactName', title: 'Your name', required: true, width: 'half', autocomplete: 'name' },
    { type: 'email', name: 'contactEmail', title: 'Email', required: true, width: 'half' },
    {
      type: 'select',
      name: 'equipment',
      title: 'Equipment',
      required: true,
      choices: [
        { value: 'hvac', text: 'Heating and air conditioning' },
        { value: 'forklift', text: 'Forklift' },
        { value: 'dock-door', text: 'Loading dock door' },
        { value: 'other', text: 'Something else' },
      ],
    },
    { type: 'text', name: 'equipmentOther', title: 'Which equipment?', visibleIf: "{equipment} = 'other'", required: true },
    {
      type: 'radio',
      name: 'urgency',
      title: 'How urgent is it?',
      required: true,
      inline: true,
      choices: ['Routine', 'Within 24 hours', 'Urgent'],
    },
    { type: 'textarea', name: 'problem', title: 'Describe the problem', required: true, rows: 4, maxLength: 2000 },
    { type: 'file', name: 'photos', title: 'Photos', accept: 'image/*', multiple: true, maxFiles: 5, maxSize: 10_000_000 },
  ],
};

const form = createForm(document.querySelector<HTMLElement>('#service-request')!, { schema: serviceRequest });

form.on('formSubmit', async ({ data }) => {
  const body = new FormData();
  for (const [key, value] of Object.entries(data)) {
    if (key === 'photos') for (const file of value as File[]) body.append('photos', file);
    else body.append(key, typeof value === 'string' ? value : JSON.stringify(value));
  }
  await fetch('/api/service-requests', { method: 'POST', body });
});
```

The `Which equipment?` question appears only when the user picks "Something else", the photos field accepts up to five images of 10 MB each, and after a valid submission the form shows the `completedMessage`.

File fields hold browser `File` objects, so send them with `FormData` rather than `JSON.stringify`. Every other value is plain JSON.

## The widget contract

`createForm(container, options)` renders into `container` and returns a `FormApi`. Like every Birch UI widget it has four core members:

| Member | Purpose |
| --- | --- |
| `element` | The form's root `<form>` element. |
| `update(partial)` | Change options in place, for example `{ locale: 'de' }`, `{ readOnly: true }` or a new `schema`. Only the keys you pass change. |
| `on(event, listener)` | Subscribe to an event. Returns an unsubscribe function. |
| `destroy()` | Remove the form and release its listeners and timers. |

On top of that it has methods to read and write values, validate, submit and navigate pages. See [Validation](https://docs.birchui.com/forms/validation.md) and [Multi-page forms](https://docs.birchui.com/forms/multi-page.md), and the full list in the [API reference](https://docs.birchui.com/api/forms.md#formapi).

```ts
form.setValue('urgency', 'Urgent');
console.log(form.getValue('urgency'));
console.log(form.getData());

const { valid, errors } = await form.validate();
const result = await form.submit();
```

### Options

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

```ts
interface FormOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `schema` | `FormSchema` |  |
| `data?` | `FormValues` |  |
| `locale?` | `string` |  |
| `messages?` | `Partial<FormMessages>` |  |
| `localeText?` | `LocaleTextInput` |  |
| `rtl?` | `boolean` |  |
| `validateOn?` | `ValidateOn` |  |
| `readOnly?` | `boolean` |  |
| `density?` | `Density` |  |
| `theme?` | `'light' \| 'dark' \| 'auto'` |  |
| `injectStyles?` | `boolean` |  |
| `functions?` | `Record<string, ExpressionFunction>` |  |
| `customValidators?` | `Record<string, CustomValidator>` |  |
| `clearHiddenValues?` | `ClearHiddenValues` |  |
| `showErrorSummary?` | `boolean` |  |
| `initialPage?` | `string \| number` |  |
| `onDraft?` | `(data: FormValues, meta: DraftMeta) => void` |  |
| `draftDelay?` | `number` |  |

`data` pre-fills the form. `onDraft` is called with the current data a short time after the user stops typing (`draftDelay`, 400 milliseconds by default), which makes auto-saving a draft a one-liner:

```ts
const saved = localStorage.getItem('service-request-draft');

createForm(container, {
  schema: serviceRequest,
  data: saved ? JSON.parse(saved) : undefined,
  onDraft: (data) => localStorage.setItem('service-request-draft', JSON.stringify(data)),
});
```

## Events

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `{ data }` | Once, right after the form is created. Listeners added immediately after `createForm()` receive it. |
| `valueChange` | `{ name, value, data }` | The user changed a value, `setValue()` was called, or a repeating entry was added or removed. |
| `formSubmit` | `{ data }` | The form was submitted and every visible field is valid. |
| `validate` | `{ valid, errors }` | A page or the whole form was validated: on **Next**, on submit and on `validate()`. |
| `pageChange` | `{ from, to, page }` | The visible page changed. `page` is the new page's name. |
| `formError` | `{ message, source? }` | A schema expression failed to parse or evaluate, a custom validator threw, or a validator is not registered. |

```ts
form.on('valueChange', ({ name, value }) => console.log(`${name} is now`, value));
form.on('formError', ({ message, source }) => reportToMonitoring('form', message, source));
```

`formError` reports problems in the form definition, never user mistakes. When nobody listens for it, the message goes to `console.warn`. The form keeps working either way: a broken condition falls back to a safe default, such as showing the question.

## Use it in your framework

Forms plugs into the same framework adapters as the grid. There is no special forms package for each framework: pass `formDefinition` to the adapter's generic factory, once, and use the result like any component. Options become props or inputs, and events become the framework's event syntax.

**React**

```tsx
import { createReactComponent } from '@birchui/react';
import { formDefinition, type FormApi } from '@birchui/forms';
import { useRef } from 'react';

export const BirchForm = createReactComponent(formDefinition);

export function ServiceRequestForm() {
  const form = useRef<FormApi>(null);
  return (
    <BirchForm
      ref={form}
      schema={serviceRequest}
      onFormSubmit={({ data }) => saveRequest(data)}
      onValueChange={({ name }) => console.log('changed', name)}
    />
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import { createVueComponent } from '@birchui/vue';
import { formDefinition } from '@birchui/forms';

const BirchForm = createVueComponent(formDefinition);
</script>

<template>
  <BirchForm :schema="serviceRequest" locale="en-GB" @form-submit="({ data }) => saveRequest(data)" />
</template>
```

**Angular**

```ts
import { Component, input, output } from '@angular/core';
import { injectBirchWidget, type WidgetOutputs } from '@birchui/angular';
import { formDefinition, type FormEvents, type FormOptions } from '@birchui/forms';

@Component({
  selector: 'app-birchui-form',
  standalone: true,
  template: '',
  styles: ':host { display: block; }',
})
export class BirchFormComponent implements WidgetOutputs<FormEvents> {
  readonly options = input.required<FormOptions>();

  readonly ready = output<FormEvents['ready']>();
  readonly valueChange = output<FormEvents['valueChange']>();
  readonly formSubmit = output<FormEvents['formSubmit']>();
  readonly validate = output<FormEvents['validate']>();
  readonly pageChange = output<FormEvents['pageChange']>();
  readonly formError = output<FormEvents['formError']>();

  private readonly widget = injectBirchWidget(formDefinition, this, () => this.options());

  get api() {
    return this.widget.instance;
  }
}
```

**Svelte**

```svelte
<script lang="ts">
  import { createSvelteAction } from '@birchui/svelte';
  import { formDefinition } from '@birchui/forms';

  const birchForm = createSvelteAction(formDefinition);
</script>

<div use:birchForm={{ schema: serviceRequest, on: { formSubmit: ({ data }) => saveRequest(data) } }}></div>
```

**Solid**

```tsx
import { createSolidComponent } from '@birchui/solid';
import { formDefinition } from '@birchui/forms';

const BirchForm = createSolidComponent(formDefinition);

export function ServiceRequestForm() {
  return <BirchForm schema={serviceRequest} onFormSubmit={({ data }) => saveRequest(data)} />;
}
```

**Web Component**

```html
<birchui-form id="service-request"></birchui-form>

<script type="module">
  import { createElementRegistration } from '@birchui/element';
  import { formDefinition } from '@birchui/forms';

  createElementRegistration(formDefinition, { requiredOptions: ['schema'] }).define();

  const element = document.querySelector('#service-request');
  element.options = { schema: serviceRequest };
  element.addEventListener('form-submit', (event) => saveRequest(event.detail.data));
</script>
```

The Web Component uses the tag name from the definition, `birchui-form`, and dispatches each event as a kebab-case `CustomEvent` with the payload in `detail`. The framework guides, starting with [React](https://docs.birchui.com/frameworks/react.md), explain refs, server rendering and typing for each adapter; everything there applies to forms too.

## Theming and density

Forms use the shared `--lq-*` design tokens, so a form matches a Birch UI grid on the same page. `theme` takes `'light'`, `'dark'` or `'auto'`, and `density` takes `'compact'`, `'comfortable'` (the default) or `'spacious'`. Form-specific tokens include `--lq-form-gap`, `--lq-form-control-height`, `--lq-form-max-width`, `--lq-form-danger` and `--lq-form-input-border`. All classes start with `lq-form`.

```css
.lq-form {
  --lq-accent: #0f766e;
  --lq-form-max-width: 720px;
  --lq-form-control-height: 40px;
}
```

## Licensing

The renderer and everything in `@birchui/forms` is MIT licensed. It never checks a license key, never shows a watermark and needs no purchase, in any number of apps.

The [Form Builder](https://docs.birchui.com/forms/builder.md), `@birchui/forms/builder`, is a commercial product: a one-time purchase of $349 per developer with free updates forever and unlimited apps and end users. You only need it if your code imports `@birchui/forms/builder`. See [Pricing](https://docs.birchui.com/getting-started/pricing.md).

## Next steps

- [Schema reference](https://docs.birchui.com/forms/schema.md) and [field types](https://docs.birchui.com/forms/field-types.md)
- [Expressions](https://docs.birchui.com/forms/expressions.md) for conditions and calculations
- [Validation](https://docs.birchui.com/forms/validation.md), [multi-page forms](https://docs.birchui.com/forms/multi-page.md) and [repeating sections](https://docs.birchui.com/forms/dynamic-panels.md)
- [Translations](https://docs.birchui.com/forms/i18n.md) and [accessibility](https://docs.birchui.com/forms/accessibility.md)
- [JSON Schema import and export](https://docs.birchui.com/forms/json-schema.md)
- [Form Builder](https://docs.birchui.com/forms/builder.md)
