Command palette

@yasinsensoy/native

React Native · Components

RichTextEditor

Rich text editor: the same document model, commands, shortcuts and value formats (HTML, Markdown, JSON) as the web RichTextEditor.

35 exports

Live example

The preview runs in the browser with the web component; the native component takes the same props and looks the same on iOS and Android.

Preview

Weekly note

This editor supports bold, italic, underline, strikethrough, inline code and highlight. There are links too.

  • Finish the design
  • Write the tests
    • Mobile
Try the Markdown shortcuts: type ## , - , 1. , [ ] , > or ```ts at the start of a line.
export function Hello({ name }: { name: string }) {
  return <p>Hello {name}!</p>;
}

Type / on an empty line to add a block, mention someone with @.

Value (html)
<h2>Weekly note</h2>
<p>This editor supports <strong>bold</strong>, <em>italic</em>, <u>underline</u>, <s>strikethrough</s>, <code>inline code</code> and <mark>highlight</mark>. There are <a href="https://github.com/yasinsensoy/ui">links</a> too.</p>
<ul data-type="task"><li data-checked="true">Finish the design</li><li data-checked="false">Write the tests<ul data-type="task"><li data-checked="false">Mobile</li></ul></li></ul>
<blockquote>Try the Markdown shortcuts: type <code>## </code>, <code>- </code>, <code>1. </code>, <code>[ ] </code>, <code>&gt; </code> or <code>```ts</code> at the start of a line.</blockquote>
<pre data-language="tsx"><code>export function Hello({ name }: { name: string }) {
  return &lt;p&gt;Hello {name}!&lt;/p&gt;;
}</code></pre>
<p>Type <code>/</code> on an empty line to add a block, mention someone with <code>@</code>.</p>

Code

import { RichTextEditor, RichTextView } from "@yasinsensoy/native";

<RichTextEditor placeholder="Write something…"
  mentions={[{ trigger: "@", items: personSearch }, { trigger: "#", items: tags }]}
  onImageUpload={async (file) => (await upload(file)).url}
  onValueChange={setContent}
/>

// To display it (server component, code blocks with CodeBlock):
<RichTextView value={content} />

Events

  1. Events appear here when you interact with the preview.

Control with a ref and RichTextView

Control with a ref

Try the buttons.

Form field (required, 280 characters, Markdown)


0/280

Markdown shortcuts work; mention with @.

Read-only display (RichTextView)

Weekly note

This editor supports bold, italic, underline, strikethrough, inline code and highlight. There are links too.

  • Finish the design
  • Write the tests
    • Mobile
Try the Markdown shortcuts: type ## , - , 1. , [ ] , > or ```ts at the start of a line.
export function Hello({ name }: { name: string }) {
  return <p>Hello {name}!</p>;
}

Type / on an empty line to add a block, mention someone with @.

Import

import {
  RichTextEditor,
  RichTextField,
  RichTextView,
  richTextToHtml,
  richTextToMarkdown,
  richTextToDocument,
  richTextToPlainText,
  isRichTextEmpty,
  defaultRichTextMessages,
  enRichTextMessages,
  DEFAULT_TOOLBAR,
} from "@yasinsensoy/native";

Rich text editor: the same document model, commands, shortcuts and value formats (HTML, Markdown, JSON) as the web RichTextEditor. No WebView; each paragraph is its own native text input, so keyboard, autocorrect, dictation and selection on iOS and Android are the system's own.

  • Formats: bold, italic, underline, strikethrough, code, highlight, link; heading 1-3, bulleted/numbered/to-do list (indent), quote, highlighted code block (language picker), image (size, caption), divider, alignment.
  • Shortcuts: # , - , 1. , [ ] , > , ``` ` ``, ---, bold`… convert as you type; deleting right after undoes it.
  • `/` menu and mentions: a suggestion list under the line; server search (cancellable) is supported.
  • Undo / redo: typing groups undo in one step (300 steps).
  • Mobile differences: a toolbar (scrolls horizontally) and the system's own selection menu replace the selection bubble; selection stays within one paragraph.
RichTextEditor({ variant, effect: _effect, value, defaultValue, onValueChange, format, placeholder, toolbar, markdownShortcuts, slashCommands, mentions, onImageUpload, maxLength, showCount, readOnly, disabled, autoFocus, invalid, "aria-label": ariaLabel, spellCheck, minHeight, maxHeight, onFocus, onBlur, messages: messagesProp, style, ref, testID, }: RichTextEditorProps): JSX.Element

Examples

<RichTextEditor format="markdown" defaultValue="**Hello**" onValueChange={setContent} />
<RichTextEditor mentions={{ items: people }} onImageUpload={async (f) => (await upload(f)).url} />

RichTextField

component

RichTextEditor with its label, description and error message. With name it binds to the nearest Form: the value is stored in the format format and the error shows on blur or on submit.

RichTextField(props: RichTextFieldProps): ReactElement<unknown, string | JSXElementConstructor<any>>

Examples

<Form schema={schema} onSubmit={save}>
  <RichTextField name="description" label="Description" format="markdown" maxLength={5000} />
  <SubmitButton>Save</SubmitButton>
</Form>

RichTextView

component

Shows rich text (HTML, Markdown or JSON). Same core and same typography as the web RichTextView and RichTextEditor; what you write looks the same as what is published.

  • Safe: HTML is not executed and no WebView is used; the content is converted to native elements. Unknown tags, scripts and unsafe URLs are dropped.
  • Headings, lists (nested, numbered, to-do), quotes, code blocks (CodeBlock), images, dividers, links and mentions.
RichTextView({ value, format, onLinkPress, onMentionPress, codeLineNumbers, fontSize, empty, style, testID, }: RichTextViewProps): JSX.Element

Examples

<RichTextView value={post.content} />
<RichTextView value={comment} format="markdown" onMentionPress={(m) => openProfile(m.id)} />

Converts rich text to HTML. The input is sanitized; the output contains only known tags and safe URLs, so it can be shown with dangerouslySetInnerHTML. Also runs on the server.

richTextToHtml(value: RichTextValue, from?: RichTextFormat): string

Examples

richTextToHtml("**Hello** _world_", "markdown"); // "<p><strong>Hello</strong> <em>world</em></p>"
richTextToHtml('<p onclick="x()">Hi<script>…</script></p>'); // "<p>Hi</p>"

Converts rich text to Markdown. Also runs on the server.

richTextToMarkdown(value: RichTextValue, from?: RichTextFormat): string

Examples

richTextToMarkdown("<h2>Title</h2><ul><li>one</li></ul>"); // "## Title\n\n- one"

Converts rich text to a RichTextDocument object. Also runs on the server; for tasks like finding mentions or counting words.

richTextToDocument(value: RichTextValue, from?: RichTextFormat): RichTextDocument

Plain text of rich text: formats are dropped and blocks are separated by line breaks. For previews, search indexes and notification texts.

richTextToPlainText(value: RichTextValue, from?: RichTextFormat): string

Examples

richTextToPlainText("<p><b>Hello</b></p><ul><li>one</li></ul>"); // "Hello\none"

Is the rich text empty? A value made only of empty paragraphs (e.g. "<p></p>") counts as empty; images and dividers count as content.

isRichTextEmpty(value: RichTextValue | null | undefined, from?: RichTextFormat): boolean

Default rich text editor messages (Turkish).

defaultRichTextMessages: RichTextMessages

English texts of the rich text editor.

enRichTextMessages: RichTextMessages

Default toolbar (same order as web).

DEFAULT_TOOLBAR: readonly RichTextToolbarItem[]

Formats that can be applied to text.

type RichTextMark = "bold" | "italic" | "underline" | "strike" | "code" | "highlight"

Texts of the rich text editor; can be changed with messages.

NameTypeDefaultDescription
editorstring"Metin düzenleyici"Screen reader name of the editing area; used when there is no label (<label for>), aria-label or placeholder.
toolbarstring"Biçimlendirme"Screen reader name of the toolbar.
undostring"Geri al"
redostring"Yinele"
blockTypestring"Metin türü"Line kind picker.
paragraphstring"Metin"
heading1string"Başlık 1"
heading2string"Başlık 2"
heading3string"Başlık 3"
boldstring"Kalın"
italicstring"İtalik"
underlinestring"Altı çizili"
strikestring"Üstü çizili"
codestring"Satır içi kod"
highlightstring"Vurgula"
linkstring"Bağlantı"
unlinkstring"Bağlantıyı kaldır"
editLinkstring"Bağlantıyı düzenle"
openLinkstring"Bağlantıyı aç"
linkPlaceholderstring"Adres yapıştır ya da yaz"Placeholder of the link box.
linkTextstring"Görünen metin"Link text box.
applystring"Uygula"
invalidLinkstring"Geçerli bir adres gir"Invalid URL.
bulletListstring"Madde işaretli liste"
orderedListstring"Numaralı liste"
taskListstring"Yapılacaklar listesi"
quotestring"Alıntı"
codeBlockstring"Kod bloğu"
imagestring"Görsel"
dividerstring"Ayırıcı çizgi"
alignstring"Hizalama"
alignLeftstring"Sola hizala"
alignCenterstring"Ortala"
alignRightstring"Sağa hizala"
alignJustifystring"İki yana yasla"
indentstring"Girintiyi artır"
outdentstring"Girintiyi azalt"
clearFormattingstring"Biçimi temizle"
languagestring"Dil"Code block language picker.
plainTextstring"Düz metin"Code block without a language.
imageUrlstring"Görsel adresi"Image URL box.
imageUploadstring"Dosyadan yükle"Image upload button.
imageAltstring"Açıklama (alt metin)"Alternative text of the image.
imageSizestring"Boyut"Image size.
smallstring"Küçük"
mediumstring"Orta"
fullstring"Tam genişlik"
removeImagestring"Görseli sil"Delete the image.
imageFailedstring"Görsel yüklenemedi"The image could not be uploaded.
insertstring"Ekle"Slash menu title.
slashHintstring"Komutlar için / yaz"Hint on an empty line.
noResultsstring"Sonuç yok"No results in the suggestion list.
loadingstring"Yükleniyor…"While suggestions are loading.
counterstring"{count}/{max}"Character counter; {count} and {max} are replaced.
tooLongstring"En fazla {max} karakter yazılabilir"When the character limit is exceeded.
wordsstring"{count} kelime"Word count; {count} is replaced.
morestring"Diğer"More tools menu.
donestring"Tamamlandı"Screen reader name of the to-do checkbox.

Built-in commands that can run in the editor (same on web and native).

type RichTextCommandName = "undo" | "redo" | "bold" | "italic" | "underline" | "strike" | "code" | "highlight" | "paragraph" | "heading1" | "heading2" | "heading3" | "bulletList" | "orderedList" | "taskList" | "quote" | "codeBlock" | "divider" | "image" | "link" | "unlink" | "alignLeft" | "alignCenter" | "alignRight" | "alignJustify" | "indent" | "outdent" | "clearFormatting"

Paragraph and heading alignment. Defaults to start (the start of the writing direction).

type RichTextAlign = "center" | "right" | "justify"

RichTextText

interface

Formatted text piece.

NameTypeDescription
type"text"Piece kind.
textstringText. Contains no line breaks outside code blocks; a line break is break.
marks?RichTextMark[]Applied formats.
link?stringLink URL.

Format of the editor value.

  • "html": sanitized HTML text. Can be shown on the page directly; contains only known tags and safe URLs.
  • "markdown": Markdown text (GFM). For places that store plain text, such as comments, READMEs or chat.
  • "json": a RichTextDocument object. The safest for processing on the server (e.g. finding mentioned people) and validating with a schema.
type RichTextFormat = "html" | "markdown" | "json"

Value type by format: a document object for json, text for the others.

type RichTextValue = string | RichTextDocument

Mention (@person, #tag). Deleted and moved as a single piece.

NameTypeDefaultDescription
type"mention"Piece kind.
idstringId of the mentioned item (e.g. user id).
labelstringDisplay name (without the trigger character).
triggerstring"@"Trigger character.

RichTextBreak

interface

Line break inside a paragraph (Shift+Enter).

NameTypeDescription
type"break"Piece kind.

Inline content piece.

type RichTextInline = RichTextText | RichTextMention | RichTextBreak

List kind: bulleted, numbered or to-do (with checkboxes).

type RichTextListStyle = "bullet" | "ordered" | "task"

List item.

NameTypeDescription
contentRichTextInline[]Text of the item.
checked?booleanChecked in a to-do list?
children?RichTextListNested list.

RichTextList

interface

List block.

NameTypeDefaultDescription
type"list"Block kind.
styleRichTextListStyleList kind.
start?number1First number of a numbered list.
itemsRichTextListItem[]Items.

Document block.

type RichTextBlock = { /** Block kind: paragraph. */ type: "paragraph"; /** Text alignment. */ align?: RichTextAlign; /** Inline content. */ content: RichTextInline[]; } | { /** Block kind: heading. */ type: "heading"; /** Heading level (h1–h3). */ level: 1 | 2 | 3; /** Text alignment. */ align?: RichTextAlign; /** Inline content. */ content: RichTextInline[]; } | { /** Block kind: quote. */ type: "quote"; /** Inline content. */ content: RichTextInline[]; } | { /** Block kind: code block. */ type: "code"; /** Highlighting language (e.g. `"tsx"`). */ language?: string; /** Code text. */ code: string; } | RichTextList | { /** Block kind: image. */ type: "image"; /** Image URL. */ src: string; /** Alternative text. */ alt?: string; /** Width as a percentage of the container (e.g. `50`). Natural size when omitted. */ width?: number; } | { /** Block kind: divider. */ type: "divider"; }

Rich text document. This is the editor value with format="json"; the safest format to store in a database and process on the server.

NameTypeDescription
type"doc"Document kind.
contentRichTextBlock[]Blocks.

Handle obtained via ref to control the editor from outside (same as web; only there is no DOM element).

NameTypeDefaultDescription
focus(): voidFocuses the editor; the caret returns to its last position.
blur(): voidDismisses the keyboard.
getValue(format?: RichTextFormat): RichTextValuethe editor's `formatReturns the value in the requested format.
getDocument(): RichTextDocumentReturns the document.
getText(): stringReturns the plain text.
setValue(value: RichTextValue, format?: RichTextFormat): voidReplaces the value (undoable).
insertContent(value: RichTextValue, format?: RichTextFormat): voidInserts content at the caret; replaces the selection if any.
insertText(text: string): voidInserts plain text at the caret.
clear(): voidClears the editor (undoable).
exec(command: RichTextCommandName): voidRuns a built-in command.
isActive(command: RichTextCommandName): booleanIs the command active? (e.g. is the caret in bold text)
insertImage(src: string, alt?: string): voidInserts an image.
setLink(href: string | null): voidApplies a link to the selection; null removes it.

Your own toolbar button (same as web; onClick is called on tap).

NameTypeDescription
keystringUnique key.
labelstringButton name (screen reader and tooltip).
iconIconPropIcon.
onClick(editor: RichTextEditorHandle) => voidCalled on tap.
isActive?(editor: RichTextEditorHandle) => booleanShould it look active? Called on every selection change.

Toolbar item: a built-in tool name, the "|" separator, or your own button. "blockType" is the text/heading picker, "align" the alignment menu.

type RichTextToolbarItem = Exclude<RichTextCommandName, "paragraph" | "heading1" | "heading2" | "heading3" | "unlink" | "alignLeft" | "alignCenter" | "alignRight" | "alignJustify"> | "blockType" | "align" | "|" | RichTextCustomTool

Mention suggestion.

NameTypeDescription
idstringId; stored in the value.
labelstringDisplay name (without the trigger).
description?ReactNodeSmall description under the name (e.g. email).
avatar?stringAvatar image URL.
icon?IconPropIcon instead of an avatar.

Mention source.

NameTypeDefaultDescription
trigger?string"@"Trigger character.
itemsreadonly RichTextMentionItem[] | ((query: string, signal: AbortSignal) => Promise<readonly RichTextMentionItem[]> | readonly RichTextMentionItem[])Suggestions: an array or a function called with the typed query (server search). The function can cancel stale searches via signal. An array is filtered by name.
label?ReactNodeList heading (e.g. "People").

Your own command to add to the slash (/) menu.

NameTypeDescription
keystringUnique key.
labelstringDisplay name.
description?ReactNodeDescription under the name.
icon?IconPropIcon.
keywords?readonly string[]Extra words to match in search.
onSelect(editor: RichTextEditorHandle) => voidCalled when chosen; the "/query" text has already been removed.

Props of the RichTextEditor component (same names as web).

NameTypeDefaultDescription
variant?"outline" | "filled" | "underline" | "ghost""outline"Field appearance.
effect?EffectPropEffect of the field box. See EffectProp.
value?RichTextValueControlled value. Its format is set by format.
defaultValue?RichTextValueUncontrolled initial value.
onValueChange?(value: RichTextValue) => voidCalled with the new value when the content changes. An empty document yields "" (an empty document in json).
format?RichTextFormat"html"Value format: "html", "markdown" or "json".
placeholder?stringPlaceholder shown while the document is empty.
toolbar?boolean | readonly RichTextToolbarItem[]trueToolbar: true shows the default tools, false hides it, an array shows only those tools (in order). Scrolls horizontally on phones.
markdownShortcuts?booleantrueMarkdown shortcuts: # heading, - list, 1. numbered list, [ ] to-do, > quote, ``` ` `` code block, --- rule, bold, italic, code , ~~strike~~, ==highlight==`. Typed addresses become links. Backspace right after a shortcut undoes it.
slashCommands?boolean | readonly RichTextSlashCommand[]trueSlash (/) menu: typing / at the start of a line or after a space opens the block insert list. An array adds your own commands after the built-in ones. false disables it.
mentions?RichTextMentionSource | readonly RichTextMentionSource[]Mention sources: @ people, # tags and so on. See RichTextMentionSource.
onImageUpload?(file: PickedFile) => Promise<string>Image uploader. When given, "Upload from file" picks from the gallery (requires @yasinsensoy/native/file-system); upload the file to your server and return its URL. The image looks faded while uploading; it is removed on error.
maxLength?numberMaximum characters. Input beyond it is blocked.
showCount?boolean | "words"Counter on the bottom line: true characters, "words" words. Turns on when maxLength is set.
readOnly?booleanRead-only: the toolbar is hidden and typing is disabled.
disabled?booleanDisabled.
autoFocus?booleanFocus when the screen opens.
required?booleanCannot be left empty in a form (whitespace only also counts as empty).
invalid?booleanMark as invalid (red border).
aria-label?stringmessages.editorScreen reader name.
spellCheck?booleantrueSpell check and autocorrect.
minHeight?number120Minimum height of the content area (pixels).
maxHeight?numberMaximum height of the content area; beyond it the editor scrolls inside and the toolbar stays visible. If omitted it grows with the content.
onFocus?() => voidOn focus.
onBlur?() => voidOn blur (from all of the editor's lines).
messages?Partial<RichTextMessages>Texts of this editor. See RichTextMessages.
style?StyleProp<ViewStyle>Container style.
ref?Ref<RichTextEditorHandle>To control the editor. See RichTextEditorHandle.
testID?stringTest id.

Props of the RichTextField component: field frame + all editor props.

type RichTextFieldProps = FieldProps & Omit<RichTextEditorProps, "invalid">

Extends: FieldProps

NameTypeDefaultDescription
variant?"outline" | "filled" | "underline" | "ghost""outline"Field appearance.
effect?EffectPropEffect of the field box. See EffectProp.
value?RichTextValueControlled value. Its format is set by format.
defaultValue?RichTextValueUncontrolled initial value.
onValueChange?(value: RichTextValue) => voidCalled with the new value when the content changes. An empty document yields "" (an empty document in json).
format?RichTextFormat"html"Value format: "html", "markdown" or "json".
placeholder?stringPlaceholder shown while the document is empty.
toolbar?boolean | readonly RichTextToolbarItem[]trueToolbar: true shows the default tools, false hides it, an array shows only those tools (in order). Scrolls horizontally on phones.
markdownShortcuts?booleantrueMarkdown shortcuts: # heading, - list, 1. numbered list, [ ] to-do, > quote, ``` ` `` code block, --- rule, bold, italic, code , ~~strike~~, ==highlight==`. Typed addresses become links. Backspace right after a shortcut undoes it.
slashCommands?boolean | readonly RichTextSlashCommand[]trueSlash (/) menu: typing / at the start of a line or after a space opens the block insert list. An array adds your own commands after the built-in ones. false disables it.
mentions?RichTextMentionSource | readonly RichTextMentionSource[]Mention sources: @ people, # tags and so on. See RichTextMentionSource.
onImageUpload?(file: PickedFile) => Promise<string>Image uploader. When given, "Upload from file" picks from the gallery (requires @yasinsensoy/native/file-system); upload the file to your server and return its URL. The image looks faded while uploading; it is removed on error.
maxLength?numberMaximum characters. Input beyond it is blocked.
showCount?boolean | "words"Counter on the bottom line: true characters, "words" words. Turns on when maxLength is set.
readOnly?booleanRead-only: the toolbar is hidden and typing is disabled.
disabled?booleanDisabled.
autoFocus?booleanFocus when the screen opens.
required?booleanCannot be left empty in a form (whitespace only also counts as empty).
aria-label?stringmessages.editorScreen reader name.
spellCheck?booleantrueSpell check and autocorrect.
minHeight?number120Minimum height of the content area (pixels).
maxHeight?numberMaximum height of the content area; beyond it the editor scrolls inside and the toolbar stays visible. If omitted it grows with the content.
onFocus?() => voidOn focus.
onBlur?() => voidOn blur (from all of the editor's lines).
messages?Partial<RichTextMessages>Texts of this editor. See RichTextMessages.
style?StyleProp<ViewStyle>Container style.
ref?Ref<RichTextEditorHandle>To control the editor. See RichTextEditorHandle.
testID?stringTest id.

Props of the RichTextView component.

NameTypeDefaultDescription
valueRichTextValue | null | undefinedContent to show: HTML, Markdown or a RichTextDocument.
format?RichTextFormatValue format. If omitted, text starting with < is treated as HTML, otherwise Markdown; an object is a JSON document.
onLinkPress?(url: string) => voidCalled when a link is pressed. If omitted, safe URLs open in the system (Linking.openURL); URLs like javascript: never become links.
onMentionPress?(mention: RichTextMention) => voidCalled when a mention (@Jane) is pressed (e.g. a profile screen). If omitted it is drawn as a label. Counterpart of mentionHref on web.
codeLineNumbers?booleanfalseLine numbers in code blocks.
fontSize?number15Body font size (pixels; scaled by device).
empty?ReactNodeElement shown when the content is empty.
style?StyleProp<ViewStyle>Container style.
testID?stringTest id.