Rich Text Editor
A rich text editor built on Tiptap with bold, italic, and link support. Pick the marks a field allows, and add your own extensions and toolbar items.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/rich-text-editor.jsonUsage
import { RichTextEditor, RichTextEditorButton } from "@/components/ui/rich-text-editor"Examples
Default
Bold, italic, and links, with a toolbar above the writing area. value and onChange deal in HTML strings, not markdown, so store what you get back as-is.
Only some marks
marks picks the formatting a field allows, and each mark gets its button. A mark left out is off for shortcuts and pastes too, so the saved HTML holds only what the field can use.
Your own toolbar items
toolbar adds items after the mark buttons and is handed the live editor. Build them from RichTextEditorButton so they match. New node types come in through extensions and need styling through className.
A whole document
variant="document" drops the field frame for a whole piece: the toolbar pins to the top while the text scrolls, and the text takes the Prose look. Put it on a card, in a ScrollFade with fade="bottom" so the fade never covers the toolbar.
States
Default, read-only and disabled side by side. Read-only sits flat on the muted fill at full opacity, hides the toolbar and still takes focus, so its text can be selected and copied; disabled dims to 70% and does not.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| value* | string | None | The editor content as an HTML string. |
| onChange* | (value: string) => void | None | Called with the updated HTML string on every edit. |
| onBlur | () => void | None | Called when the editor loses focus. |
| placeholder | string | None | Placeholder text shown when the editor is empty. |
| disabled | boolean | false | Turns the editor off: not editable, not focusable, toolbar disabled, dimmed to 70% like a disabled Textarea. Inside a Field the field's own disabled does the same. |
| readOnly | boolean | false | Shows the content without letting it be changed: flat on the muted fill at full opacity, toolbar hidden, still focusable so the text can be selected and copied. Ignored while disabled. |
| marks | ("bold" | "italic" | "link")[] | ["bold", "italic", "link"] | The marks the editor applies, each with its toolbar button. A mark left out is off for shortcuts and pastes too. An empty list with no toolbar hides the toolbar. Read once, on mount. |
| extensions | Extensions | None | More Tiptap extensions, added after the kit's own. Read once, on mount. |
| toolbar | (editor: Editor | null) => ReactNode | None | More toolbar items after the mark buttons, given the live editor (null until it mounts). |
| variant | "field" | "document" | "field" | field is a form field framed like a Textarea. document is a whole piece with no frame: the toolbar is a band across the whole surface, pinned to the top of the scroll area, and its buttons and the text share one reading column in the Prose look. Read once, on mount. |
| activeRichTextEditorButton | boolean | None | Fills the button with the accent tint and sets aria-pressed. Leave it off for a button that is not a toggle. Takes Button's other props; give it an aria-label and a size-3 icon. |
| className | string | None | Extra classes for the editor's outer container. |
| id | string | None | Id for the editable area, for a <label htmlFor> outside a Field. Inside a Field the id comes from the field. |
| aria-label / aria-labelledby / aria-describedby / aria-invalid | string | boolean | None | Put on the editable area. Inside a Field the label, help and error links and the invalid state arrive on their own, and clicking the label focuses the editor. |
| value*stringThe editor content as an HTML string. |
| onChange*(value: string) => voidCalled with the updated HTML string on every edit. |
| onBlur() => voidCalled when the editor loses focus. |
| placeholderstringPlaceholder text shown when the editor is empty. |
disabledboolean = falseTurns the editor off: not editable, not focusable, toolbar disabled, dimmed to 70% like a disabled Textarea. Inside a Field the field's own disabled does the same. |
readOnlyboolean = falseShows the content without letting it be changed: flat on the muted fill at full opacity, toolbar hidden, still focusable so the text can be selected and copied. Ignored while disabled. |
marks("bold" | "italic" | "link")[] = ["bold", "italic", "link"]The marks the editor applies, each with its toolbar button. A mark left out is off for shortcuts and pastes too. An empty list with no toolbar hides the toolbar. Read once, on mount. |
| extensionsExtensionsMore Tiptap extensions, added after the kit's own. Read once, on mount. |
| toolbar(editor: Editor | null) => ReactNodeMore toolbar items after the mark buttons, given the live editor (null until it mounts). |
variant"field" | "document" = "field"field is a form field framed like a Textarea. document is a whole piece with no frame: the toolbar is a band across the whole surface, pinned to the top of the scroll area, and its buttons and the text share one reading column in the Prose look. Read once, on mount. |
activeRichTextEditorButtonbooleanFills the button with the accent tint and sets aria-pressed. Leave it off for a button that is not a toggle. Takes Button's other props; give it an aria-label and a size-3 icon. |
| classNamestringExtra classes for the editor's outer container. |
idstringId for the editable area, for a <label htmlFor> outside a Field. Inside a Field the id comes from the field. |
aria-label / aria-labelledby / aria-describedby / aria-invalidstring | booleanPut on the editable area. Inside a Field the label, help and error links and the invalid state arrive on their own, and clicking the label focuses the editor. |
"use client"
import * as React from "react"
import { Field as FieldPrimitive } from "@base-ui/react/field"
import { useEditor, useEditorState, EditorContent, type Editor, type Extensions } from "@tiptap/react"
import StarterKit from "@tiptap/starter-kit"
import Link from "@tiptap/extension-link"
import Placeholder from "@tiptap/extension-placeholder"
import { IconBold as Bold, IconItalic as Italic, IconLink as LinkIcon, IconUnlink as Unlink } from "@tabler/icons-react"
import { useCallback, useEffect, useState } from "react"
import { cn } from "@/registry/lib/utils"
import { Button } from "@/registry/ui/button"
import { Input } from "@/registry/ui/input"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/registry/ui/popover"
/** A formatting mark the editor can apply. Each one that is on gets its button. */
type RichTextEditorMark = "bold" | "italic" | "link"
const ALL_MARKS: RichTextEditorMark[] = ["bold", "italic", "link"]
interface RichTextEditorProps {
value: string
onChange: (value: string) => void
onBlur?: () => void
placeholder?: string
className?: string
/** Id for the editable area, for a `<label htmlFor>` outside a `Field`. Inside
* a `Field` the id comes from the field and this is not needed. */
id?: string
"aria-label"?: string
"aria-labelledby"?: string
"aria-describedby"?: string
"aria-invalid"?: React.AriaAttributes["aria-invalid"]
/** Turns the editor off: not editable, not focusable, toolbar disabled, dimmed
* to 70% like a disabled Textarea. Inside a `Field` the field's own disabled
* state does the same. For a field that does not apply right now. */
disabled?: boolean
/** Shows the content without letting it be changed: flat on the muted fill at
* full opacity, still focusable so the text can be selected and copied, and
* the toolbar is hidden since there is nothing to format. For a value someone
* should see but not edit. */
readOnly?: boolean
/** Which marks the editor applies, each with its toolbar button. A mark left
* out is off everywhere: no button, no shortcut, and pasted text loses it,
* so the saved HTML only holds what the field can use. Read once, on mount. */
marks?: RichTextEditorMark[]
/** More Tiptap extensions, added after the kit's own. Read once, on mount. */
extensions?: Extensions
/** More toolbar items after the mark buttons, given the live editor (null
* until it mounts). Build them from `RichTextEditorButton` so they match. */
toolbar?: (editor: Editor | null) => React.ReactNode
/** `field` (default): a form field, framed like a Textarea. `document`: a
* whole piece of writing on the surface it sits in, with no frame. The
* toolbar is a band across the whole surface, pinned to the top of the
* scrolling area; its buttons and the text share one reading column
* (Prose, 16px inset, 20px top and bottom). Put it edge to edge on a card
* surface inside a scroll area (`ScrollFade` fades the bottom). Read once,
* on mount. */
variant?: "field" | "document"
}
// The link between the editor and a Field. Base UI hands a control its id, its
// label link, its help and error links and the invalid state through
// `Field.Control`, but that renders an input and the editable area is a div
// that Tiptap owns. So Control renders this instead, which draws nothing and
// passes the props up for Tiptap to put on its editable element.
type LinkedProps = Pick<
RichTextEditorProps,
"id" | "aria-label" | "aria-labelledby" | "aria-describedby" | "aria-invalid" | "disabled"
>
function FieldLink({
fieldProps,
onProps,
}: {
fieldProps: React.HTMLProps<HTMLElement>
onProps: (props: LinkedProps) => void
}) {
const { id, "aria-label": label, "aria-labelledby": labelledBy, "aria-describedby": describedBy, "aria-invalid": invalid, disabled } = fieldProps
React.useEffect(() => {
onProps({
id,
"aria-label": label,
"aria-labelledby": labelledBy,
"aria-describedby": describedBy,
"aria-invalid": invalid,
disabled: !!disabled,
})
}, [onProps, id, label, labelledBy, describedBy, invalid, disabled])
return null
}
/**
* One toolbar button: a 28px ghost icon button that fills with the accent tint
* while `active`. The editor's own Bold, Italic and Link are these, so an item
* passed through `toolbar` matches them. Give it an `aria-label` and a `size-3`
* icon; pass `active` only for a toggle, which also sets `aria-pressed`.
*/
export function RichTextEditorButton({
active,
className,
...props
}: Omit<React.ComponentProps<typeof Button>, "variant" | "size"> & { active?: boolean }) {
return (
<Button
type="button"
variant="ghost"
size="icon"
aria-pressed={active}
// The toolbar keeps its own touch size. `size="icon"` grows to a 44px box
// on a coarse pointer and carries the 44px corner with it, but the band is
// 36px tall, so a 44px control would overflow it. Each button holds the
// 36px override and therefore owes its own corner: the 32px rung is the
// closest fit. It is forced because every radius utility inside the
// coarse media query is emitted in name order, so the wider rung would
// otherwise win on nothing but its letters.
className={cn(
"h-7 w-7 rounded-action-sm pointer-coarse:size-9 pointer-coarse:!rounded-action",
active && "bg-accent-100 dark:bg-accent-700 text-accent-700 dark:text-accent-100",
className
)}
{...props}
/>
)
}
// @use-when authoring formatted text. Inside a `Field` it takes the label,
// help and error links and the invalid state like a text field does, and a
// click on the label focuses it. `marks` picks which formatting it allows.
export function RichTextEditor({
value,
onChange,
onBlur,
placeholder,
className,
id,
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledBy,
"aria-describedby": ariaDescribedBy,
"aria-invalid": ariaInvalid,
disabled = false,
readOnly = false,
marks = ALL_MARKS,
extensions,
toolbar,
variant = "field",
}: RichTextEditorProps) {
const isDocument = variant === "document"
const [linked, setLinked] = useState<LinkedProps>({})
// Disabled wins over read-only: a field that does not apply is not a value to read.
const isDisabled = disabled || !!linked.disabled
const isReadOnly = readOnly && !isDisabled
const editable = !isDisabled && !isReadOnly
const rootRef = React.useRef<HTMLDivElement>(null)
const [linkUrl, setLinkUrl] = useState("")
const [linkPopoverOpen, setLinkPopoverOpen] = useState(false)
const hasBold = marks.includes("bold")
const hasItalic = marks.includes("italic")
const hasLink = marks.includes("link")
const editor = useEditor({
immediatelyRender: false,
extensions: [
StarterKit.configure({
// A mark that is off is left out of the schema, so a shortcut or a
// paste cannot bring it back.
bold: hasBold ? undefined : false,
italic: hasItalic ? undefined : false,
heading: false,
bulletList: false,
orderedList: false,
listItem: false,
blockquote: false,
codeBlock: false,
code: false,
horizontalRule: false,
hardBreak: false,
link: false,
}),
...(hasLink
? [
Link.configure({
openOnClick: false,
HTMLAttributes: {
class: "text-accent underline decoration-from-font underline-offset-2",
},
}),
]
: []),
Placeholder.configure({
placeholder,
}),
...(extensions ?? []),
],
content: value,
editable,
editorProps: {
attributes: {
// Undefined values are left off by Tiptap, so a bare editor adds nothing.
...(linked.id ? { id: linked.id } : {}),
...(linked["aria-label"] ? { "aria-label": linked["aria-label"] } : {}),
...(linked["aria-labelledby"] ? { "aria-labelledby": linked["aria-labelledby"] } : {}),
...(linked["aria-describedby"] ? { "aria-describedby": linked["aria-describedby"] } : {}),
...(linked["aria-invalid"] ? { "aria-invalid": String(linked["aria-invalid"]) } : {}),
"aria-multiline": "true",
...(isDisabled ? { "aria-disabled": "true" } : {}),
// A read-only editor stays in the tab order so its text can be selected
// and copied; a disabled one does not.
...(isReadOnly ? { "aria-readonly": "true", tabindex: "0" } : {}),
class: cn(
// The focus ring is drawn on the field's own box (the wrapper below
// reads this element's :focus-visible), so the editable area adds none.
"outline-none",
isDocument
? // A document reads like the finished piece: Prose owns the type
// and the space between blocks, at Card's content inset.
"prose-ui mx-auto box-content min-h-36 px-4 py-5"
: cn(
"min-h-36 px-3 py-2 text-field md:text-sm",
"[&_p]:my-0 [&_p:not(:last-child)]:mb-2",
"[&_strong]:font-semibold [&_em]:italic"
)
),
},
},
onUpdate: ({ editor }) => {
onChange(editor.getHTML())
},
onBlur: () => {
onBlur?.()
},
})
// Sync external value changes
useEffect(() => {
if (editor && value !== editor.getHTML()) {
editor.commands.setContent(value)
}
}, [editor, value])
// Tiptap reads `editable` once at init, so push later changes in.
useEffect(() => {
if (editor && editor.isEditable !== editable) editor.setEditable(editable)
}, [editor, editable])
// Keep the placeholder reactive: the extension reads it once at init, so push
// later prop changes into its options and force a redraw.
useEffect(() => {
if (!editor) return
const ext = editor.extensionManager.extensions.find((e) => e.name === "placeholder")
if (ext && ext.options.placeholder !== placeholder) {
ext.options.placeholder = placeholder
editor.view.dispatch(editor.state.tr)
}
}, [editor, placeholder])
const handleSetLink = useCallback(() => {
if (!editor) return
if (linkUrl === "") {
editor.chain().focus().extendMarkRange("link").unsetLink().run()
} else {
editor
.chain()
.focus()
.extendMarkRange("link")
.setLink({ href: linkUrl })
.run()
}
setLinkUrl("")
setLinkPopoverOpen(false)
}, [editor, linkUrl])
const handleOpenLinkPopover = useCallback(() => {
if (!editor) return
const previousUrl = editor.getAttributes("link").href || ""
setLinkUrl(previousUrl)
setLinkPopoverOpen(true)
}, [editor])
// The toolbar follows the cursor: read on every transaction (Tiptap does not
// re-render on its own, so a one-time read left Bold or Italic stuck as they
// were at mount). A mark shows as on only while the text has focus: before
// that the cursor is not on screen, and it sits wherever loading left it,
// often the end of the text, so a button lit for it reads as a setting.
const marksOn = useEditorState({
editor,
selector: ({ editor: e }) => {
const focused = e?.isFocused ?? false
return {
bold: focused && (e?.isActive("bold") ?? false),
italic: focused && (e?.isActive("italic") ?? false),
link: focused && (e?.isActive("link") ?? false),
}
},
})
const isLinkActive = hasLink && (marksOn?.link ?? false)
const extraItems = toolbar?.(editor)
// No marks and no extra items leave nothing to press, so the band goes too.
const showToolbar = !isReadOnly && (marks.length > 0 || extraItems != null)
return (
<div
ref={rootRef}
data-slot="rich-text-editor"
data-invalid={linked["aria-invalid"] && linked["aria-invalid"] !== "false" ? "" : undefined}
data-disabled={isDisabled ? "" : undefined}
data-readonly={isReadOnly ? "" : undefined}
data-variant={variant}
className={cn(
isDocument
? // No frame: the surface it sits on is the page. Disabled still dims.
"data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-70"
: cn(
"rounded-action border border-border bg-input-bg bg-clip-padding backdrop-blur-sm shadow-xs transition-[color,box-shadow,border-color] duration-small ease-small",
// Hover darkens the border one step, as on Input; focus and invalid sort
// after it. Only the editable area lights the field on focus: a toolbar
// button carries its own ring, so the field box stays quiet for it.
"hover:border-border-strong",
"has-[.ProseMirror:focus-visible]:border-border-focus",
"data-[invalid]:border-destructive",
// Disabled dims a field to 70% and blocks the pointer, like Textarea.
"data-[disabled]:pointer-events-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-70 data-[disabled]:bg-muted data-[disabled]:shadow-none",
// Read-only: flat on the muted fill, full opacity, still focusable.
"data-[readonly]:bg-muted data-[readonly]:shadow-none data-[readonly]:hover:border-border"
),
className
)}
>
<FieldPrimitive.Control
id={id}
// Only the ones given. An explicit `undefined` here would overwrite the
// label link the field puts on its control, leaving the editable area
// with no accessible name.
{...(ariaLabel !== undefined ? { "aria-label": ariaLabel } : {})}
{...(ariaLabelledBy !== undefined ? { "aria-labelledby": ariaLabelledBy } : {})}
{...(ariaDescribedBy !== undefined ? { "aria-describedby": ariaDescribedBy } : {})}
{...(ariaInvalid !== undefined ? { "aria-invalid": ariaInvalid } : {})}
disabled={disabled}
render={(fieldProps) => <FieldLink fieldProps={fieldProps} onProps={setLinked} />}
/>
{/* Toolbar. Hidden when read-only: nothing to format, and a row of dead
buttons says "editable". Kept, but disabled, when disabled. */}
{showToolbar && (
<div
role="group"
aria-label="Formatting"
className={cn(
"border-b border-border",
isDocument
? // A band across the whole surface, pinned while the piece
// scrolls under it, on the card it sits on. Its buttons sit in
// the same reading column as the text below.
"sticky top-0 z-10 bg-card"
: "flex items-center gap-0.5 px-1 py-1 h-9"
)}
>
<div className={isDocument ? "mx-auto box-content flex h-9 max-w-measure items-center gap-0.5 px-4 py-1 text-base" : "contents"}>
{hasBold && (
<RichTextEditorButton
active={marksOn?.bold ?? false}
onClick={() => editor?.chain().focus().toggleBold().run()}
disabled={!editor || isDisabled}
aria-label="Bold"
>
<Bold className="size-3" />
</RichTextEditorButton>
)}
{hasItalic && (
<RichTextEditorButton
active={marksOn?.italic ?? false}
onClick={() => editor?.chain().focus().toggleItalic().run()}
disabled={!editor || isDisabled}
aria-label="Italic"
>
<Italic className="size-3" />
</RichTextEditorButton>
)}
{hasLink && (
<Popover open={linkPopoverOpen && !isDisabled} onOpenChange={setLinkPopoverOpen}>
<PopoverTrigger
render={
<RichTextEditorButton
active={isLinkActive}
onClick={handleOpenLinkPopover}
disabled={!editor || isDisabled}
aria-label="Link"
>
<LinkIcon className="size-3" />
</RichTextEditorButton>
}
/>
{/* Anchored to the whole editor and opened below it, so the popover
never sits over the text the link is being set on. */}
<PopoverContent className="w-80 p-2" align="start" side="bottom" sideOffset={8} anchor={rootRef}>
<div className="flex gap-2">
<Input
aria-label="Link address"
value={linkUrl}
onChange={(e) => setLinkUrl(e.target.value)}
placeholder="https://example.com"
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault()
handleSetLink()
}
}}
/>
{/* Default size, not `sm` forced to h-8: that combination kept
`sm`'s 10.5px corner on a 32px box, so this button and the
Input beside it were the same height with different radii.
Only the padding is tightened. */}
<Button
type="button"
className="px-3"
onClick={handleSetLink}
>
{linkUrl ? "Set" : "Remove"}
</Button>
</div>
</PopoverContent>
</Popover>
)}
{isLinkActive && (
<RichTextEditorButton
onClick={() => editor?.chain().focus().unsetLink().run()}
disabled={isDisabled}
aria-label="Remove link"
>
<Unlink className="size-3" />
</RichTextEditorButton>
)}
{extraItems}
</div>
</div>
)}
{/* Editor content area - fixed height whether editor loaded or not */}
<div className="min-h-36">
{editor && (
<EditorContent editor={editor} />
)}
</div>
</div>
)
}