Examples

Reply with validation

Submit empty to see the error. Select text and press Ctrl/⌘ + B, or Alt + F10 for the toolbar.

Preview

The customer receives this by email.

Alt+F10 moves to the formatting toolbar.
Example.tsx
import { RichTextEditor, isEmptyDocument, type RichTextDocument } from '@reactloom/editor';
import { Button, Stack } from '@reactloom/ui';
import { useState } from 'react';

export default function Example() {
  const [body, setBody] = useState<RichTextDocument | null>(null);
  const [error, setError] = useState<string>();
  return (
    <form
      style={{ width: '100%', maxWidth: 560 }}
      onSubmit={(e) => {
        e.preventDefault();
        setError(isEmptyDocument(body) ? 'Write a reply before sending.' : undefined);
      }}
    >
      <Stack gap="3">
        <RichTextEditor
          label="Reply"
          description="The customer receives this by email."
          placeholder="Write a reply…"
          required
          error={error}
          value={body}
          onValueChange={(doc) => {
            setBody(doc);
            setError(undefined);
          }}
          name="body"
        />
        <Stack direction="row" justify="end">
          <Button type="submit">Send reply</Button>
        </Stack>
      </Stack>
    </form>
  );
}

More formats

formats decides the toolbar and what the document may contain; pasted formatting outside it is dropped.

Preview

Alt+F10 moves to the formatting toolbar.
Example.tsx
import { RichTextEditor } from '@reactloom/editor';

export default function Example() {
  return (
    <div style={{ width: '100%', maxWidth: 640 }}>
      <RichTextEditor
        label="Release notes"
        formats={['bold', 'italic', 'code', 'link', 'heading', 'bulletList', 'orderedList', 'blockquote', 'codeBlock']}
        headingLevels={[2, 3]}
        placeholder="What changed in this release?"
        minHeight={200}
        maxHeight={360}
      />
    </div>
  );
}

Images and tables

Put the caret in the table for row and column buttons; arrow keys move between cells and Tab leaves the field. Images need alternative text or an explicit “decorative”.

Preview

Escalation contacts

Team

Contact

Hours

Billing

billing@example.com

9–17

Platform

oncall@example.com

24/7

Alt+F10 moves to the formatting toolbar.
Example.tsx
import { RichTextEditor, type RichTextDocument } from '@reactloom/editor';

const cell = (type: 'tableHeader' | 'tableCell', text: string) => ({ type, content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] });

const runbook: RichTextDocument = {
  type: 'doc',
  content: [
    { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Escalation contacts' }] },
    {
      type: 'table',
      content: [
        { type: 'tableRow', content: [cell('tableHeader', 'Team'), cell('tableHeader', 'Contact'), cell('tableHeader', 'Hours')] },
        { type: 'tableRow', content: [cell('tableCell', 'Billing'), cell('tableCell', 'billing@example.com'), cell('tableCell', '9–17')] },
        { type: 'tableRow', content: [cell('tableCell', 'Platform'), cell('tableCell', 'oncall@example.com'), cell('tableCell', '24/7')] },
      ],
    },
  ],
};

export default function Example() {
  return (
    <div style={{ width: '100%', maxWidth: 640 }}>
      <RichTextEditor label="Runbook" formats={['bold', 'italic', 'link', 'heading', 'bulletList', 'image', 'table']} defaultValue={runbook} />
    </div>
  );
}

The stored value

Edit the note: the JSON is what you store, renderHtml is what the server sends to other people.

Preview

Invoice INV-2042 is paid. Receipt on the billing page.

Alt+F10 moves to the formatting toolbar.
Stored value (JSON)
{
  "type": "doc",
  "content": [
    {
      "type": "paragraph",
      "content": [
        {
          "type": "text",
          "text": "Invoice INV-2042 is "
        },
        {
          "type": "text",
          "marks": [
            {
              "type": "bold"
            }
          ],
          "text": "paid"
        },
        {
          "type": "text",
          "text": ". Receipt on the "
        },
        {
          "type": "text",
          "marks": [
            {
              "type": "link",
              "attrs": {
                "href": "https://example.com/billing"
              }
            }
          ],
          "text": "billing page"
        },
        {
          "type": "text",
          "text": "."
        }
      ]
    }
  ]
}
renderHtml(doc) — what the server sends
<p>Invoice INV-2042 is <strong>paid</strong>. Receipt on the <a rel="noopener noreferrer nofollow" href="https://example.com/billing">billing page</a>.</p>
Example.tsx
import { RichTextEditor, renderHtml, type RichTextDocument } from '@reactloom/editor';
import { CodeBlock, Stack } from '@reactloom/ui';
import { useState } from 'react';

const initial: RichTextDocument = {
  type: 'doc',
  content: [
    {
      type: 'paragraph',
      content: [
        { type: 'text', text: 'Invoice INV-2042 is ' },
        { type: 'text', marks: [{ type: 'bold' }], text: 'paid' },
        { type: 'text', text: '. Receipt on the ' },
        { type: 'text', marks: [{ type: 'link', attrs: { href: 'https://example.com/billing' } }], text: 'billing page' },
        { type: 'text', text: '.' },
      ],
    },
  ],
};

export default function Example() {
  const [doc, setDoc] = useState<RichTextDocument>(initial);
  return (
    <Stack gap="3" style={{ width: '100%', maxWidth: 640 }}>
      <RichTextEditor label="Note" value={doc} onValueChange={setDoc} minHeight={80} />
      <CodeBlock code={JSON.stringify(doc, null, 2)} language="json" title="Stored value (JSON)" maxLines={10} />
      <CodeBlock code={renderHtml(doc)} language="html" title="renderHtml(doc) — what the server sends" wrap />
    </Stack>
  );
}

Storing and showing content safely

Rich text is content from one user that other users will see, so the package draws the boundary for you (ADR-0011). Store the JSON document, never HTML sent by a browser — anyone can send a request that skips the editor. On the server, validateDocument checks the document against the field’s formats and checks every link (the editor’s schema alone would accept a javascript: address). To display it, renderHtml turns the JSON into HTML without needing a browser environment, and your HTML sanitiser removes anything unexpected as a second line of defence.

Server: validate, store JSON, render
// app/api/replies/route.ts — never accept HTML from the client.
import { validateDocument, renderHtml } from '@reactloom/editor/server';
import DOMPurify from 'isomorphic-dompurify'; // or sanitize-html

export async function POST(request: Request) {
  const { body } = await request.json();
  // Same formats as the field. Rejects unknown nodes, unsafe links (javascript:, data:) and long text.
  const result = validateDocument(body, { formats: ['bold', 'italic', 'link', 'bulletList', 'orderedList'], maxLength: 10_000 });
  if (!result.valid) return Response.json({ errors: result.errors }, { status: 422 });

  await db.replies.insert({ body: result.doc, text: result.text }); // store JSON (+ plain text for search)
  return Response.json({ ok: true });
}

// When showing it to someone else: render on the server, then sanitise as defence in depth.
const html = DOMPurify.sanitize(renderHtml(reply.body));

API reference

RichTextEditor props

RichTextEditor props
PropTypeDefault
labelrequired
Names the editable area.
ReactNode—
value / defaultValue / onValueChange
Store the JSON, not HTML.
RichTextDocument (JSON)—
formats
Also: strike, code, heading, blockquote, codeBlock, image, table.
RichTextFormat[]bold, italic, link, bulletList, orderedList
headingLevels
(1–6)[][2, 3]
allowRelativeLinks
Accept /paths and #anchors.
booleanfalse
description · error · invalid · required
Field states, wired to the editable area.
—
disabled · readOnly
Read-only hides the toolbar; text stays selectable.
booleanfalse
placeholder
Also exposed as aria-placeholder.
string—
name
Submits the JSON in a hidden input.
string—
minHeight · maxHeight
Scrolls inside beyond maxHeight.
number | string120 · –
toolbar
Keyboard shortcuts still work without it.
booleantrue
messages
Translate every built-in string.
Partial<EditorMessages>—

Functions (also from @reactloom/editor/server)

Functions
PropTypeDefault
validateDocument(json, { formats, maxLength, allowRelativeLinks })
Server boundary: nodes, marks, links, length.
{ valid, doc, text } | { valid: false, errors }—
renderHtml(json, options)
DOM-free HTML; drops unsafe links; throws on invalid documents.
string—
isEmptyDocument(json)
For required checks.
boolean—
isSafeUrl(url) · normalizeUrl(text)
http, https and mailto only; “example.com” → https://example.com.
—

Customization

Extracted from the component’s source on every build, so it matches the code. How the layers fit together is explained in Customization.

State attributes

Target these in your CSS to style states without depending on class names.

AttributeValues
[data-disabled]present when on
[data-invalid]present when on
[data-readonly]present when on
[data-separator]present when on

Theme tokens it reads

--pl-color-accent-fg --pl-color-accent-subtle --pl-color-bg-muted --pl-color-bg-subtle --pl-color-bg-surface --pl-color-border-default --pl-color-border-focus --pl-color-border-input --pl-color-border-strong --pl-color-danger-border --pl-color-fg-default --pl-color-fg-disabled --pl-color-fg-link --pl-color-fg-muted --pl-color-fg-subtle --pl-focus-ring-color --pl-focus-ring-width --pl-font-size-lg --pl-font-size-md --pl-font-size-xl --pl-font-size-xs --pl-radius-md --pl-radius-sm --pl-radius-xs

Accessibility

  • The editable area is a multiline textbox named by the label and described by the description, the error and a hint about the toolbar; required, invalid, read-only and disabled states are exposed.
  • The toolbar follows the WAI-ARIA toolbar pattern: one tab stop, ← / → between buttons (mirrored in right-to-left layouts), Home / End, and Escape back to the text. Alt + F10 jumps to it from the text. Format buttons are toggle buttons (aria-pressed) and list their shortcuts in aria-keyshortcuts.
  • Pressing a toolbar button with the mouse keeps the text selection, so formatting applies where you expect.
  • The link dialog only accepts web and email addresses and explains why when it refuses one.
  • Images need alternative text, or an explicit “decorative” choice (stored as an empty alt); validateDocument rejects images with neither, and sources other than http(s).
  • Tables start with a header row rendered as column headers (th scope="col"). Arrow keys move between cells; Tab is not captured, so it still leaves the field. Row and column buttons appear in the toolbar while the caret is in a table.
  • Before JavaScript loads, the server renders the document as read-only HTML in the same box, so content is readable immediately and nothing shifts.
Keyboard interactions
KeyAction
Ctrl/⌘ + B · IBold · italic
Ctrl/⌘ + KAdd or edit a link
Ctrl/⌘ + Shift + 8 · 7Bulleted · numbered list
Ctrl/⌘ + Z · Shift + ZUndo · redo
Alt + F10Move to the toolbar
← / → (toolbar)Previous / next button
Escape (toolbar)Back to the text

Usage guidelines

Do

  • Allow only the formats the content needs; fewer buttons are faster to learn.
  • Validate on the server with the same formats as the field.

Don’t

  • Don’t store or display HTML sent by the browser.
  • Don’t use rich text for short single-line values — use Input or Textarea.