# React Native Rich Text Editor (Pro)

> A Notion-style rich text editor for React Native, iOS, Android and the web: blocks, a / command menu, @mentions, Markdown shortcuts, a floating or keyboard toolbar, links, drag to reorder, undo and redo, Markdown and JSON output, read-only rendering and a Linear-style comment composer. Part of Patine Pro, React Native core only: no WebView.

# RichTextEditor Pro

`RichTextEditor` is a block editor in the style of Notion: every paragraph, heading, list item, to-do, quote, code block, callout, image and divider is its own block. Type `/` for a menu of blocks, `@` to mention someone, or plain Markdown (`# `, `- `, `[] `, `**bold**`) and it formats as you go. Select text for the toolbar, drag a block by its handle, and undo anything. The value is plain JSON you can store as is, and `toMarkdown` turns it into GitHub-flavored Markdown. Use it for docs, notes, issue descriptions and long comments; for a quick message, the free [TextArea](./text-area) is enough.

React Native's `TextInput` can't mix styles on its own, and a WebView editor costs a second runtime on every platform, so each block is its own input that draws its marks inside the text as you type (styled text children on iOS and Android, styled text under a transparent text area on the web): real formatting while you write, with React Native core only.

```tsx
import { RichTextEditor, CommentComposer, toMarkdown, fromMarkdown } from '@patine-ui/pro';
```

```tsx live wide
import { RichTextEditor } from '@patine-ui/pro';

const PEOPLE = [
  { id: 'maya', label: 'Maya Chen', description: 'Design lead' },
  { id: 'omar', label: 'Omar Haddad', description: 'iOS engineer' },
  { id: 'lena', label: 'Lena Fischer', description: 'Product manager' },
  { id: 'sam', label: 'Sam Okafor', description: 'Backend' },
];

const SPEC = `# Offline sync

Ship **offline-first** editing in the mobile app by _October 14_. Owner: [@Lena Fischer](mention:lena). The data model is in the [RFC](https://patine.dev).

> [!TIP]
> Conflicts resolve per field, last write wins. Lists merge by id.

## Milestones

- [x] Local store on SQLite
- [x] Queue writes while offline
- [ ] Sync in the background on reconnect
   - [ ] Retry with backoff
- [ ] Conflict banner in the editor

## Rollout

1. A week of internal dogfooding
2. 10% of iOS users
3. Everyone

\`\`\`ts
await sync.flush({ retry: 3 });
\`\`\`

---

> Offline should feel like nothing happened. — Maya`;

export default function Example() {
  return <RichTextEditor defaultValue={SPEC} mentions={PEOPLE} showCount style={{ width: '100%', maxWidth: 760 }} />;
}
```

Try it: select a few words for the toolbar, press Enter at the end of a to-do, type `/` on an empty line, `@ma` anywhere, or `**word**`. Hover a block on the web for its **+** and drag handle.

## Example: a job posting

A hiring tool's job editor: the posting starts from a template, and the checklist beside it reads the document as you write, so Publish waits for the sections every posting needs.

```tsx live
import { useState } from 'react';
import { View } from 'react-native';
import { Button, HStack, Text, VStack } from 'patine-ui';
import { Icon, RichTextEditor, countText, fromMarkdown, toMarkdown } from '@patine-ui/pro';

const TEMPLATE = `# Senior iOS Engineer

Join the team that builds **Ledger** for 40,000 small shops. Remote in Europe, or at our Lisbon office.

## What you'll do

- Own the offline sync in the iOS app
- Pair with design on the new checkout

## Salary

€85,000 – €105,000, plus equity.`;

const CHECKS = [
  { label: 'What you’ll do', test: (md: string) => /^## What you.ll do/m.test(md) },
  { label: 'What we look for', test: (md: string) => /^## What we look for/m.test(md) },
  { label: 'Salary range', test: (md: string) => /€\d/.test(md) },
];

export default function Example() {
  const [doc, setDoc] = useState(() => fromMarkdown(TEMPLATE));
  const md = toMarkdown(doc);
  const { words } = countText(doc);
  const ready = CHECKS.every((c) => c.test(md));
  return (
    <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 16, width: '100%' }}>
      <View style={{ flex: 2, minWidth: 280 }}>
        <RichTextEditor value={doc} onChange={setDoc} placeholder="Describe the role" />
      </View>
      <VStack gap="sm" style={{ flex: 1, minWidth: 200 }}>
        <Text weight="semibold">Before you publish</Text>
        {CHECKS.map((c) => (
          <HStack key={c.label} gap="xs" align="center">
            <Icon name={c.test(md) ? 'checkCircle' : 'alertCircle'} size="sm" color={c.test(md) ? 'success' : 'warning'} />
            <Text size="sm">{c.label}</Text>
          </HStack>
        ))}
        <Text size="sm" color="textSecondary">{words} words · aim for 300 to 700</Text>
        <Button disabled={!ready}>{ready ? 'Publish posting' : 'Add the missing parts'}</Button>
      </VStack>
    </View>
  );
}
```

## Typing

Markdown typed at the start of a block turns it into another kind; Markdown typed around a word formats it the moment it closes.

| Type | Becomes |
| --- | --- |
| `# `, `## `, `### ` | Heading 1, 2, 3 |
| `- ` or `* ` | Bulleted list |
| `1. ` | Numbered list |
| `[] ` or `[x] ` | To-do |
| `> ` | Quote |
| ` ``` ` | Code block (Enter on an empty last line leaves it) |
| `---` | Divider |
| `**bold**`, `*italic*`, `~~strike~~`, `` `code` `` | The mark, without the markers |

Enter splits a block (a list continues; Enter on an empty item ends the list), Shift+Enter adds a line inside it, Backspace at the start of a block turns it back into text and then joins it to the one above, and Tab and Shift+Tab nest list items. On the web: Cmd/Ctrl+B, I, E (code), K (link), Shift+X (strike), Z and Shift+Z (undo and redo), and the arrow keys move between blocks.

## Commands and mentions

`/` opens the block menu wherever a word could start; keep typing to filter it, then pick with the arrows and Enter, or a tap. `@` does the same with `mentions`: people, pages, issues, anything with an `id` and a `label`. A mention is one piece in the text, stored with its id (`[@Maya Chen](mention:maya)` in Markdown), and `onMentionPress` hears presses on it in read-only mode.

```tsx live
import { useState } from 'react';
import { Text, VStack } from 'patine-ui';
import { RichTextEditor, BLOCK_COMMANDS } from '@patine-ui/pro';

const TEAM = [
  { id: 'u1', label: 'Ada Lovelace', description: 'ada@acme.com' },
  { id: 'u2', label: 'Grace Hopper', description: 'grace@acme.com' },
  { id: 'u3', label: 'Alan Turing', description: 'alan@acme.com' },
];

// Only the blocks a support macro needs, in your order.
const COMMANDS = BLOCK_COMMANDS.filter((c) => ['paragraph', 'heading2', 'bullet', 'todo', 'callout', 'divider'].includes(c.type));

export default function Example() {
  const [pressed, setPressed] = useState('');
  return (
    <VStack gap="sm" style={{ width: '100%', maxWidth: 560 }}>
      <RichTextEditor
        defaultValue={'Thanks for reporting this! Looping in [@Grace Hopper](mention:u2).\n\nType / or @ here…'}
        mentions={TEAM}
        commands={COMMANDS}
        onMentionPress={(m) => setPressed(m.label)}
      />
      {pressed ? <Text size="sm" color="textSecondary">Pressed {pressed}</Text> : null}
    </VStack>
  );
}
```

## Value and Markdown

The value is a `RichTextDoc`: `{ blocks: [{ id, type, text, marks?, checked?, indent?, language?, url?, tone? }] }`. Marks are ranges over a block's plain text (`{ type: 'bold', start: 0, end: 4 }`), so the JSON stays readable and diffable. Control it with `value` and `onChange`, or start from a doc or a Markdown string with `defaultValue`. `toMarkdown(doc)` writes GitHub-flavored Markdown (task lists, callouts as `> [!NOTE]` alerts) and `fromMarkdown(markdown)` reads it back; pasting Markdown with line breaks into the editor makes blocks too.

```tsx live
import { useState } from 'react';
import { View, ScrollView } from 'react-native';
import { Text, VStack } from 'patine-ui';
import { RichTextEditor, toMarkdown, fromMarkdown, countText } from '@patine-ui/pro';

export default function Example() {
  const [doc, setDoc] = useState(() => fromMarkdown('## Release notes\n\n- **Faster** sync on cold start\n- Fixed `null` crash in the share sheet\n\nThanks to everyone who reported it.'));
  const { words } = countText(doc);
  return (
    <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 16, width: '100%' }}>
      <View style={{ flex: 1, minWidth: 280 }}>
        <RichTextEditor value={doc} onChange={setDoc} />
      </View>
      <VStack gap="xs" style={{ flex: 1, minWidth: 280 }}>
        <Text size="xs" color="textSecondary">Markdown · {words} words</Text>
        <ScrollView style={{ maxHeight: 260 }}>
          <Text style={{ fontFamily: 'Menlo, monospace', fontSize: 12, lineHeight: 18 }}>{toMarkdown(doc)}</Text>
        </ScrollView>
      </VStack>
    </View>
  );
}
```

## Read-only

`readOnly` renders the same document with no inputs: links open (or call `onLinkPress`), mentions call `onMentionPress`, and checkboxes show their state. Use it for published docs, comment threads and previews, from the same JSON or Markdown you store.

```tsx live
import { RichTextEditor } from '@patine-ui/pro';

const POST = `## Incident report: 12 minutes of failed logins

On **March 3** between 14:02 and 14:14 UTC, about 8% of sign-ins failed. Owner: [@Sam Okafor](mention:sam).

> [!WARNING]
> Tokens issued during the window were revoked. Affected users signed in again.

### Follow-ups

- [x] Roll back the session store change
- [ ] Add a canary for token refresh
- [ ] Page on-call at a 2% error rate, not 5%`;

export default function Example() {
  return <RichTextEditor readOnly defaultValue={POST} style={{ width: '100%', maxWidth: 640 }} />;
}
```

## Comment composer

`CommentComposer` is the editor in a framed box with a toolbar, an attach button and a send button: the comment box of Linear and GitHub. Cmd/Ctrl+Enter sends. `onSubmit` gets the doc and its Markdown, and the box clears unless it returns `false` (or a promise of `false`), so a failed request keeps the text. Put chips or thumbnails in `attachments`; set `allowEmpty` to send attachments alone.

```tsx live
import { useState } from 'react';
import { View } from 'react-native';
import { Avatar, Button, HStack, Text, VStack } from 'patine-ui';
import { CommentComposer, Icon, RichTextEditor } from '@patine-ui/pro';

const PEOPLE = [
  { id: 'maya', label: 'Maya Chen', description: 'Design lead' },
  { id: 'omar', label: 'Omar Haddad', description: 'iOS engineer' },
  { id: 'lena', label: 'Lena Fischer', description: 'Product manager' },
];

const FIRST = [
  { id: 'c1', author: 'Maya Chen', time: '2h', body: 'The banner reads well in dark mode now. Can we **ship** it behind the `offline_v2` flag first?' },
  { id: 'c2', author: 'Omar Haddad', time: '48m', body: 'Done in [#412](https://patine.dev). [@Lena Fischer](mention:lena) can you flip it for the beta group?' },
];

function Comment({ comment }) {
  return (
    <HStack gap="sm" style={{ alignItems: 'flex-start' }}>
      <Avatar name={comment.author} size={32} />
      <VStack gap="xs" style={{ flex: 1 }}>
        <HStack gap="xs">
          <Text size="sm" weight="medium">{comment.author}</Text>
          <Text size="sm" color="textSecondary">{comment.time}</Text>
        </HStack>
        <RichTextEditor readOnly defaultValue={comment.body} />
      </VStack>
    </HStack>
  );
}

export default function Example() {
  const [comments, setComments] = useState(FIRST);
  const [files, setFiles] = useState([]);
  const send = async (_doc, markdown) => {
    await new Promise((resolve) => setTimeout(resolve, 500));
    setComments((all) => [...all, { id: String(Date.now()), author: 'You', time: 'now', body: markdown }]);
    setFiles([]);
  };
  return (
    <VStack gap="lg" style={{ width: '100%', maxWidth: 620 }}>
      {comments.map((c) => <Comment key={c.id} comment={c} />)}
      <CommentComposer
        mentions={PEOPLE}
        onSubmit={send}
        onAttach={() => setFiles((f) => [...f, `screenshot-${f.length + 1}.png`])}
        attachments={files.length ? (
          <HStack gap="xs" style={{ flexWrap: 'wrap' }}>
            {files.map((f) => (
              <View key={f} style={{ paddingHorizontal: 10, paddingVertical: 4, borderRadius: 999, borderWidth: 1, borderColor: 'rgba(127,127,127,0.3)' }}>
                <HStack gap="xs" align="center">
                  <Icon name="paperclip" size={12} />
                  <Text size="xs">{f}</Text>
                </HStack>
              </View>
            ))}
          </HStack>
        ) : null}
      />
    </VStack>
  );
}
```

## Toolbar

On the web the toolbar floats over a selection, Notion style; on phones it docks above the keyboard (an input accessory on iOS) while the editor has focus. `toolbarMode` picks either anywhere. `toolbar` lists the buttons in order, `'|'` for a divider, or `false` for none: `bold`, `italic`, `strike`, `code`, `link`, `heading1`, `heading2`, `bullet`, `numbered`, `todo`, `quote`, `mention`, `undo`, `redo`. Each button shows whether its mark or block type is on at the caret. With nothing selected, a mark button applies to what you type next.

```tsx live
import { RichTextEditor } from '@patine-ui/pro';

export default function Example() {
  return (
    <RichTextEditor
      defaultValue="Click here: the toolbar under this text stays while the editor has focus."
      toolbarMode="docked"
      toolbar={['bold', 'italic', 'code', 'link', '|', 'bullet', 'numbered', 'quote', '|', 'undo', 'redo']}
      reorderable={false}
      style={{ width: '100%', maxWidth: 560, borderWidth: 1, borderColor: 'rgba(127,127,127,0.25)', borderRadius: 12 }}
    />
  );
}
```

## Images

The `/image` command asks for a URL in a dialog. Pass `onPickImage` to use your own picker and upload instead: resolve the uploaded URL, or `null` to cancel. Images keep their aspect ratio and take a caption.

```tsx live
import { RichTextEditor } from '@patine-ui/pro';

const pick = () => new Promise((resolve) => setTimeout(() => resolve('https://picsum.photos/seed/patine/1200/700'), 400));

export default function Example() {
  return (
    <RichTextEditor
      onPickImage={pick}
      defaultValue={'## Moodboard\n\nType /image on the empty line below.\n\n![Morning light on the studio wall](https://picsum.photos/seed/studio/1200/600)'}
      style={{ width: '100%', maxWidth: 640 }}
    />
  );
}
```

## Accessibility

- Every block is a real text input with a name for screen readers (its placeholder: "Heading 1", "To-do"…); headings render with the heading role and level in read-only mode, and to-dos are checkboxes.
- The toolbar has the toolbar role; its buttons are named with their shortcut on the web ("Bold (⌘B)") and report `aria-pressed`. The menus are listboxes whose options report `aria-selected`.
- Everything works from the keyboard on the web: the menus' arrows, Enter, Tab and Escape, mark shortcuts, Tab to nest lists, arrows between blocks. Blocks also reorder with the keyboard (focus a row, Space, arrows, Space) and with the screen reader's Move up and Move down actions.
- Touch targets are 44pt with hit slop; the drag handle shows on hover or on the focused block.

## Props

### RichTextEditor

| Prop | Type | Default |
| --- | --- | --- |
| `value` | `RichTextDoc` | |
| `defaultValue` | `RichTextDoc` \| `string` (Markdown) | One empty paragraph |
| `onChange` | `(doc) => void`, user changes only | |
| `readOnly` | `boolean` | `false` |
| `placeholder` | `string`, the focused empty paragraph's hint | `"Type '/' for commands"` |
| `mentions` | `MentionItem[]`: `{ id, label, description?, avatar? }` | Mentions off |
| `commands` | `BlockCommand[]` | `BLOCK_COMMANDS` |
| `toolbar` | `ToolbarItem[]` \| `false` | Marks, link, headings, lists, undo, redo |
| `toolbarMode` | `'floating'` \| `'docked'` | Floating on the web, docked on phones |
| `toolbarEnd` | `ReactNode`, after the docked toolbar's buttons (it then always shows) | |
| `showCount` | `boolean`, words and characters | `false` |
| `reorderable` | `boolean`, drag handles | `true` |
| `onPickImage` | `() => Promise<string \| null>` | A URL dialog |
| `onLinkPress` | `(href) => void`, read-only | Opens http, mailto and tel links |
| `onMentionPress` | `({ id, label }) => void` | |
| `onSubmit` | `() => void`, Cmd/Ctrl+Enter | |
| `onFocusChange` | `(focused) => void` | |
| `autoFocus` | `boolean` | `false` |
| `menuPlacement` | `'auto'` \| `'above'` | `'auto'` |
| `scrollEnabled` | `boolean`, scroll inside a fixed height | `false` (grows) |
| `contentPadding` | `number` | Theme spacing |
| `labels` | `Partial<EditorLabels>` | English |
| `accessibilityLabel`, `style`, `testID`, `theme`, `design` | | |

### CommentComposer

| Prop | Type | Default |
| --- | --- | --- |
| `onSubmit` | `(doc, markdown) => boolean \| void \| Promise<…>`; `false` keeps the text | |
| `value`, `defaultValue`, `onChange` | As on the editor | |
| `placeholder` | `string` | `'Leave a comment…'` |
| `mentions` | `MentionItem[]` | |
| `toolbar` | `ToolbarItem[]` | Bold, italic, code, link, lists, mention |
| `onAttach` | `() => void`; shows the paperclip | |
| `attachments` | `ReactNode`, above the toolbar | |
| `allowEmpty` | `boolean` | `false` |
| `submitting` | `boolean` | `false` |
| `submitLabel` | `string` | `'Comment'` |
| `footerStart` | `ReactNode`, before the attach and send buttons | |
| `menuPlacement` | `'auto'` \| `'above'`, for a box docked at the bottom of a screen | `'auto'` |
| `autoFocus`, `disabled`, `labels`, `style`, `testID`, `theme`, `design` | | |

## Related

- [TextArea](./text-area): plain multi-line text, free.
- [AI Chat](../blocks/ai-chat): its composer for prompts, and Markdown rendering for replies.
- [Messenger](../blocks/messenger): a chat thread with replies and reactions.
