# Markdown Editor

> React markdown editor with a toolbar that wraps the selection, shortcuts, write, split and preview modes, a live preview without innerHTML and a word count.

- Kind: Component (Forms)
- Docs: https://ui.minidev.pro/docs/markdown-editor
- Source (registry JSON with the full file): https://ui.minidev.pro/r/markdown-editor.json
- License: MIT. One file, yours to edit after install.

## When to use

Use it for release notes, comments, descriptions and docs fields. For rendering markdown only use MarkdownRenderer (or the exported MarkdownPreview), for rich text without markdown syntax use RichTextToolbar, and for chat input use PromptInput. Works controlled (value + onChange) or uncontrolled (defaultValue).

## Installation

### shadcn CLI (copies the source into your project)

```bash
npx shadcn@latest add @minidev/markdown-editor
```

Writes `components/ui/markdown-editor.tsx` plus the MiniDev files it is built from (segmented-control) and installs its npm dependencies. Older CLI versions: `npx shadcn@latest add https://ui.minidev.pro/r/markdown-editor.json`.

### npm package

```bash
npm i minidev-ui-kit lucide-react
```

Add the tokens to your global stylesheet once:

```css
@import "tailwindcss";
@import "minidev-ui-kit/styles.css";
@source "../node_modules/minidev-ui-kit";
```

Next.js also needs `transpilePackages: ["minidev-ui-kit"]` in next.config.

## Import

After the shadcn install:

```tsx
import { MarkdownEditor, MarkdownPreview } from "@/components/ui/markdown-editor"
```

From the npm package:

```tsx
import { MarkdownEditor } from "minidev-ui-kit/ui/markdown-editor"
```

## Usage

```tsx
import { MarkdownEditor } from "@/components/ui/markdown-editor"

export function Example() {
  return (
    <MarkdownEditor />
  )
}
```

## Props

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `value` | `string` | - | no | Markdown text (controlled). |
| `defaultValue` | `string` | `SAMPLE` | no | Initial markdown when uncontrolled. Defaults to sample release notes. |
| `onChange` | `(value: string) => void` | - | no | Called with the full text on every edit and toolbar action. |
| `mode` | `MarkdownEditorMode` | - | no | View (controlled): write shows the textarea, preview the rendered result, split both. |
| `defaultMode` | `MarkdownEditorMode` | `"split"` | no | Initial view when uncontrolled. |
| `onModeChange` | `(mode: MarkdownEditorMode) => void` | - | no | Called when the view changes. |
| `label` | `string` | `"Release notes"` | no | Accessible name for the textarea. |
| `placeholder` | `string` | `"Write in markdown…"` | no | Shown in the empty textarea. |
| `minHeight` | `number` | `300` | no | Editor and preview height in px before the textarea is resized. |
| `disabled` | `boolean` | - | no |  |
| `className` | `string` | - | no |  |
| `name` | `string` | - | no | Submits the markdown under this name in a hidden input, so it is sent in every mode, including preview. No name by default. |

## Examples

### Controlled value

value and onChange make the text yours, so save and discard buttons can compare it with what is stored.

```tsx
const TEMPLATE = `## Summary

Northwind's September invoice is **$1,840.00** over the quote.

## Steps to reproduce

1. Open INV-2041
2. Compare the usage line with the metering export

## Expected

Usage should match the \`2.4M\` calls in the export.`

function ControlledDemo() {
  const [value, setValue] = React.useState(TEMPLATE)
  const [saved, setSaved] = React.useState(TEMPLATE)
  const dirty = value !== saved
  return (
    <div className="flex w-full max-w-3xl flex-col gap-3">
      <MarkdownEditor value={value} onChange={setValue} defaultMode="write" label="Issue description" minHeight={200} />
      <div className="flex items-center justify-between gap-3">
        <p className="text-xs text-fg-muted">{dirty ? "Unsaved changes" : "Saved"}</p>
        <div className="flex gap-2">
          <Button size="sm" variant="outline" disabled={!dirty} onClick={() => setValue(saved)}>Discard</Button>
          <Button size="sm" disabled={!dirty} onClick={() => setSaved(value)}>Save</Button>
        </div>
      </div>
    </div>
  )
}
```

### Preview only

MarkdownPreview is exported on its own for rendering stored markdown, built from React elements and never from HTML strings.

```tsx
const POLICY = `## Refund policy

Refunds are issued to the **original payment method** within 5 business days.

- Annual plans: prorated for the unused months
- Monthly plans: refundable within 14 days of the charge
- Usage fees are *not* refundable once metered

> Disputes should go to [billing@lumen.app](mailto:billing@lumen.app) with the invoice number, for example INV-2041.`

<div className="w-full max-w-lg rounded-xl border border-border bg-surface p-5 shadow-raised">
  <MarkdownPreview source={POLICY} />
</div>
```

### Empty, write mode

An empty defaultValue with a placeholder is the starting point for a comment box; the preview is one click away.

```tsx
<MarkdownEditor defaultValue="" defaultMode="write" placeholder="Describe the change for the release notes…" label="Release note" minHeight={140} className="max-w-xl" />
```

## Keyboard interactions

| Key | Action |
| --- | --- |
| `Cmd+B` or `Ctrl+B` | In the textarea, wraps or unwraps the selection in bold. |
| `Cmd+I` or `Ctrl+I` | In the textarea, wraps or unwraps the selection in italics. |
| `Cmd+E` or `Ctrl+E` | In the textarea, wraps or unwraps the selection as inline code. |
| `Cmd+K` or `Ctrl+K` | In the textarea, inserts a link and selects the part to edit. The key does not reach a global command palette. |
| `ArrowLeft` or `ArrowRight` | In the formatting toolbar, moves between tools and wraps at the ends. |
| `Home` or `End` | In the formatting toolbar, moves to the first or last tool. |

## Accessibility

- The tools sit in a `role="toolbar"` named "Formatting" with one Tab stop. Each tool's name includes its shortcut, such as "Bold (⌘B)" on a Mac or "Bold (Ctrl+B)" elsewhere.
- Bold, Italic and Code get `aria-pressed="true"` when the selection is already wrapped in that mark.
- The textarea is named by a visually hidden `<label>` from `label` (default "Release notes").
- The preview is a `role="region"` named "Preview". It is not a live region, so it is not re-read on every keystroke.

## FAQ

### Why does the editor start with release notes in it?

`defaultValue` defaults to sample text. Pass `defaultValue=""`, or control it with `value` and `onChange`.

### Is the preview safe from XSS?

The preview builds React elements and never sets `innerHTML`, so raw HTML shows as text. Links are kept only for `http(s)`, `mailto:`, `/`, `#` and `./` or `../` paths; any other target, such as `javascript:`, keeps its text but loses the link. External links open in a new tab with `rel="noopener noreferrer"`.

### Which Markdown does it support?

Headings, paragraphs, bold, italic, strikethrough, inline code, fenced code blocks, quotes, bulleted and numbered lists, horizontal rules and links. Tables, images and task lists are not parsed, and indented list items are flattened into one level.

### Does it submit with a form?

Pass `name` and the markdown is submitted under it. The value travels in a hidden input rather than on the textarea, so it is sent in preview mode too, when the textarea is not rendered.

## Rules for generating code

- Use semantic tokens only (bg, surface, sunken, border, fg, fg-muted, fg-subtle, ink, accent, success, warning, danger). Never raw hex or palette steps like blue-500.
- Shadows only from the set: shadow-xs, shadow-sm, shadow-raised, shadow-md, shadow-lg, shadow-overlay.
- Numbers use tabular-nums. Dark mode is the `dark` class on <html>; components never branch on theme.

## Dependencies

- npm: `lucide-react`
- Built from: [segmented-control](https://ui.minidev.pro/docs/segmented-control/md)

## Related

- [Markdown Renderer](https://ui.minidev.pro/docs/markdown-renderer/md): A small React renderer for AI output that splits text into paragraphs on blank lines and turns fenced code blocks into scrollable monospace panels.
- [Rich Text Toolbar](https://ui.minidev.pro/docs/rich-text-toolbar/md): Formatting toolbar with bold and italic toggles, link, bullet and numbered list buttons, and a divider. Uses role toolbar with labelled icon toggles in React.
- [Prompt Input](https://ui.minidev.pro/docs/prompt-input/md): An AI chat composer that grows with its content, sends on Enter, adds a newline on Shift Enter and has attach, toolbar and send controls. Built for React.
- [Character Count](https://ui.minidev.pro/docs/character-count/md): Live React character counter that shows the current count against a limit and turns red when it goes over. Announces changes politely to screen readers.
- [Textarea](https://ui.minidev.pro/docs/textarea/md): Multiline textarea with a 96px minimum height, comfortable line height, hairline border, focus ring and subtle placeholder. A shadcn-compatible Textarea.
- [Autocomplete](https://ui.minidev.pro/docs/autocomplete/md): Text input that filters string options as you type, using ARIA combobox and listbox roles. Works controlled or uncontrolled and lists up to eight matches.

---

All 557 components: https://ui.minidev.pro/llms.txt (full text: https://ui.minidev.pro/llms-full.txt).
