# Frameworks

> Use Birch UI Document Editor in React, Vue, Angular, Svelte and Solid and as a custom element through the /document entry point of each adapter, with typed options, events and the editor API.

Every adapter package has a `/document` entry point with a ready-made editor component. It wraps `documentEditorDefinition` (name `BirchDocumentEditor`, tag `birchui-document-editor`), so each component takes the options of [`createDocumentEditor`](https://docs.birchui.com/document/api.md), reports the same events and hands out the same `DocumentEditorApi`. The entry point is the only code in the adapter that imports `@birchui/document`, which stays an optional peer dependency: apps that only use the grid never load editor code.

## Install

```bash
npm install @birchui/document @birchui/core @birchui/react
```

Replace `@birchui/react` with `vue`, `angular`, `svelte`, `solid` or `element` as needed.

| Framework | Import |
| --- | --- |
| React 18 and later | `import { BirchDocumentEditor } from '@birchui/react/document'` |
| Vue 3.3 and later | `import { BirchDocumentEditor } from '@birchui/vue/document'` |
| Angular 17.3 and later | `import { BirchDocumentEditorComponent } from '@birchui/angular/document'` |
| Svelte 5 | `import { BirchDocumentEditor, birchDocumentEditor } from '@birchui/svelte/document'` |
| Solid 1.8 and later | `import { BirchDocumentEditor } from '@birchui/solid/document'` |
| Custom element | `import { defineBirchDocumentEditor } from '@birchui/element/document'` |
| JavaScript | `import { createDocumentEditor } from '@birchui/document'` |

Three rules hold in every framework:

- **Give the editor a height.** It fills its container. Size the component with a class or a style, or pass the `height` option; see [Troubleshooting](https://docs.birchui.com/document/troubleshooting.md).
- **Keep `content` stable.** The adapters compare options by identity and call `update()` with the ones that changed, and `update({ content })` replaces the document. Hold the initial document in a constant or in state that changes only when another document is opened, not in state that you replace while the user types, and read the current document with `getJSON()`.
- **Leave teardown to the adapter.** It calls `destroy()` when the component goes away, which removes every listener, observer and timer.

Importing `@birchui/document` or an adapter never touches `window` or `document`, so the modules below are safe to import during server-side rendering. The editor itself is created in the browser.

## Shared options for the examples

All examples edit a supply agreement with track changes on. The options and the helpers live in one module, so each framework file only holds what is specific to the framework.

```ts title="contract-options.ts"
import type { DocumentData, DocumentEditorEvents, DocumentEditorOptions } from '@birchui/document';

export const contractOptions: DocumentEditorOptions = {
  author: 'Priya Raman',
  trackChanges: true,
  ruler: true,
  placeholder: 'Start with the parties to the agreement',
};

export async function fetchDraft(): Promise<DocumentData> {
  const response = await fetch('/api/contracts/supply-agreement');
  if (!response.ok) throw new Error(`The draft could not be loaded (${response.status})`);
  return (await response.json()) as DocumentData;
}

export function storeDraft(data: DocumentData): void {
  void fetch('/api/contracts/supply-agreement', {
    method: 'PUT',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(data),
  });
}

export function wordStatus({ wordCount }: DocumentEditorEvents['contentChange']): string {
  return `${wordCount} words`;
}
```

## React

Every option is a prop, every event is an `on…` prop and `ref` receives the `DocumentEditorApi`.

```tsx title="ContractEditor.tsx"
import { useRef, useState } from 'react';
import type { DocumentData, DocumentEditorApi } from '@birchui/document';
import { BirchDocumentEditor } from '@birchui/react/document';
import { contractOptions, storeDraft, wordStatus } from './contract-options';

export function ContractEditor({ draft, isSigned }: { draft: DocumentData; isSigned: boolean }) {
  const editor = useRef<DocumentEditorApi>(null);
  const [initial] = useState(draft);
  const [status, setStatus] = useState('');

  return (
    <>
      <button type="button" onClick={() => void editor.current?.downloadDocx('Supply agreement')}>
        Download as Word
      </button>
      <span>{status}</span>
      <BirchDocumentEditor
        ref={editor}
        style={{ height: 720 }}
        {...contractOptions}
        content={initial}
        readOnly={isSigned}
        onContentChange={(event) => {
          setStatus(wordStatus(event));
          if (editor.current) storeDraft(editor.current.getJSON());
        }}
      />
    </>
  );
}
```

The component creates the editor in a layout effect and destroys it on unmount, so it survives the double mount of React's strict mode. `readOnly` changes go to `update()`; the editor is not created again. Handlers may change on every render; the component always calls the latest one.

## Vue

Options are attributes or one `options` object, events are emitted with kebab-case names (`contentChange` becomes `content-change`) and the component exposes `api`.

```vue title="ContractEditor.vue"
<script setup lang="ts">
import { ref } from 'vue';
import type { DocumentData, DocumentEditorApi, DocumentEditorEvents } from '@birchui/document';
import { BirchDocumentEditor } from '@birchui/vue/document';
import { contractOptions, storeDraft, wordStatus } from './contract-options';

const props = defineProps<{ draft: DocumentData; isSigned: boolean }>();

const editor = ref<{ api: DocumentEditorApi | null } | null>(null);
const initial = props.draft;
const status = ref('');

function save(event: DocumentEditorEvents['contentChange']) {
  status.value = wordStatus(event);
  const api = editor.value?.api;
  if (api) storeDraft(api.getJSON());
}
</script>

<template>
  <button type="button" @click="editor?.api?.downloadDocx('Supply agreement')">Download as Word</button>
  <span>{{ status }}</span>
  <BirchDocumentEditor
    ref="editor"
    style="height: 720px"
    :options="contractOptions"
    :content="initial"
    :read-only="isSigned"
    @content-change="save"
  />
</template>
```

The editor is created in `onMounted` and destroyed in `onBeforeUnmount`. An attribute wins over the same key in `options`. `initial` is a plain constant on purpose: a reactive value that is replaced on every keystroke would send `content` again.

## Angular

`<birchui-document-editor>` is a standalone `OnPush` component. It takes `options` plus the shortcut inputs `content`, `readOnly`, `author`, `trackChanges`, `showMarkup`, `zoom`, `layout` and `licenseKey`, has one output per editor event and returns the `DocumentEditorApi` from its `api` property.

```ts title="contract-editor.component.ts"
import { ChangeDetectionStrategy, Component, input, signal, viewChild } from '@angular/core';
import { BirchDocumentEditorComponent } from '@birchui/angular/document';
import type { DocumentData, DocumentEditorEvents } from '@birchui/document';
import { contractOptions, storeDraft, wordStatus } from './contract-options';

@Component({
  selector: 'app-contract-editor',
  standalone: true,
  imports: [BirchDocumentEditorComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <button type="button" (click)="download()">Download as Word</button>
    <span>{{ status() }}</span>
    <birchui-document-editor
      style="height: 720px"
      [options]="options"
      [content]="draft()"
      [readOnly]="isSigned()"
      (contentChange)="save($event)"
    />
  `,
})
export class ContractEditorComponent {
  readonly draft = input.required<DocumentData>();
  readonly isSigned = input(false);
  readonly status = signal('');
  readonly options = contractOptions;

  private readonly editor = viewChild.required(BirchDocumentEditorComponent);

  save(event: DocumentEditorEvents['contentChange']): void {
    this.status.set(wordStatus(event));
    const api = this.editor().api;
    if (api) storeDraft(api.getJSON());
  }

  download(): void {
    void this.editor().api?.downloadDocx('Supply agreement');
  }
}
```

The editor is created in `afterNextRender`, which only runs in the browser, and runs outside the Angular zone. An output re-enters the zone only when it emits and something listens to it. The component has outputs named `focus` and `blur` because the editor has events with those names; they report the editor, not the DOM event.

## Svelte

`BirchDocumentEditor` is a component with a bindable `api`; `birchDocumentEditor` is the same thing as an action for an element you own.

```svelte title="ContractEditor.svelte"
<script lang="ts">
  import type { DocumentData, DocumentEditorApi } from '@birchui/document';
  import { BirchDocumentEditor } from '@birchui/svelte/document';
  import { contractOptions, storeDraft, wordStatus } from './contract-options';

  let { draft, isSigned }: { draft: DocumentData; isSigned: boolean } = $props();

  const initial = draft;
  let api = $state.raw<DocumentEditorApi | null>(null);
  let status = $state('');
</script>

<button type="button" onclick={() => api?.downloadDocx('Supply agreement')}>Download as Word</button>
<span>{status}</span>

<BirchDocumentEditor
  bind:api
  style="height: 720px"
  {...contractOptions}
  content={initial}
  readOnly={isSigned}
  onContentChange={(event) => {
    status = wordStatus(event);
    if (api) storeDraft(api.getJSON());
  }}
/>
```

The action takes the options plus `on`, a map of event handlers, and `onReady`, which receives the API:

```svelte title="ContractEditorAction.svelte"
<script lang="ts">
  import type { DocumentData, DocumentEditorApi } from '@birchui/document';
  import { birchDocumentEditor } from '@birchui/svelte/document';
  import { contractOptions, storeDraft } from './contract-options';

  let { draft }: { draft: DocumentData } = $props();

  let editor: DocumentEditorApi | null = null;
  const params = {
    ...contractOptions,
    content: draft,
    onReady: (api: DocumentEditorApi) => (editor = api),
    on: { contentChange: () => editor && storeDraft(editor.getJSON()) },
  };
</script>

<div use:birchDocumentEditor={params} style="height: 720px"></div>
```

Neither form runs during server rendering: the component renders an empty container and actions are skipped, so the same files work in SvelteKit.

## Solid

Options are props, events are `on…` props and `ref` receives the API once the editor exists.

```tsx title="ContractEditor.tsx"
import { createSignal } from 'solid-js';
import type { DocumentData, DocumentEditorApi } from '@birchui/document';
import { BirchDocumentEditor } from '@birchui/solid/document';
import { contractOptions, storeDraft, wordStatus } from './contract-options';

export function ContractEditor(props: { draft: DocumentData; isSigned: boolean }) {
  const [status, setStatus] = createSignal('');
  const initial = props.draft;
  let editor: DocumentEditorApi | undefined;

  return (
    <>
      <button type="button" onClick={() => void editor?.downloadDocx('Supply agreement')}>
        Download as Word
      </button>
      <span>{status()}</span>
      <BirchDocumentEditor
        ref={(api) => (editor = api)}
        style={{ height: '720px' }}
        {...contractOptions}
        content={initial}
        readOnly={props.isSigned}
        onContentChange={(event) => {
          setStatus(wordStatus(event));
          if (editor) storeDraft(editor.getJSON());
        }}
      />
    </>
  );
}
```

One effect tracks every option and sends the changed keys to `update()` in one call. The editor is created in `onMount`.

## Custom element

`defineBirchDocumentEditor()` registers `<birchui-document-editor>`. Set the options through the `options` property or one at a time with `set(key, value)`; events are bubbling `CustomEvent`s with kebab-case names and the payload in `detail`; `api` is the editor.

```ts title="contract-editor.ts"
import { defineBirchDocumentEditor } from '@birchui/element/document';
import { contractOptions, fetchDraft, storeDraft, wordStatus } from './contract-options';

defineBirchDocumentEditor();

export async function mountContractEditor(host: HTMLElement, status: HTMLElement): Promise<void> {
  const editor = document.createElement('birchui-document-editor');
  editor.style.cssText = 'display: block; height: 720px';
  editor.options = { ...contractOptions, content: await fetchDraft() };
  editor.addEventListener('content-change', (event) => {
    status.textContent = wordStatus(event.detail);
    if (editor.api) storeDraft(editor.api.getJSON());
  });
  host.append(editor);
}

export function lockContract(editor: HTMLElementTagNameMap['birchui-document-editor']): void {
  editor.set('readOnly', true);
}
```

The editor is created when the element is connected and has at least one option, or when you call `create()`, and it is destroyed when the element is removed from the document and not inserted again in the same task. There is no Shadow DOM: the editor's styles are injected into the document as usual. `defineBirchDocumentEditor()` does nothing on the server and returns `undefined`.

## Without an adapter

The components are thin: they call `createDocumentEditor`, send changed options to `update()` and call `destroy()`. In a framework without an adapter, do the same in its mount and unmount hooks.

```ts
import { createDocumentEditor, type DocumentData, type DocumentEditorApi } from '@birchui/document';

export function mountEditor(host: HTMLElement, draft: DocumentData): DocumentEditorApi {
  return createDocumentEditor(host, { content: draft, author: 'Priya Raman', trackChanges: true });
}

export function unmountEditor(editor: DocumentEditorApi): void {
  editor.destroy();
}
```

The generic factories of the adapters (`createReactComponent`, `createVueComponent`, `createSvelteAction`, `createSolidComponent`, `createElementRegistration`) still accept `documentEditorDefinition`, so components written against them before the `/document` entry points existed keep working.

## What is checked

- The plain `ts` sample of this page is compiled with the samples of the other Document Editor pages by `packages/document/test/docs-samples.test.ts`, against the real types of `@birchui/document`.
- The titled `ts` and `tsx` samples (the shared module, React, Angular, Solid and the custom element) are compiled together by `packages/document/test/framework-samples.test.ts`, against the sources of `@birchui/document` and of the `/document` entry point of each adapter. The Angular sample is checked by the TypeScript compiler only, not by the Angular compiler.
- The Vue and Svelte single-file components are not compiled by either test, because neither has a Vue or Svelte compiler; the module they import is.
- Each adapter has a test that mounts the real editor through its `/document` entry point, changes an option, receives an event and unmounts: `packages/<adapter>/test/document.test.ts` (`document.test.tsx` for React), and `packages/angular/test/document-editor.component.test.ts` for the Angular inputs and outputs.
