RichTextEditor

RichTextEditor is a native WYSIWYG text editor. Component state and the public API live in C#; browser editing operations (contenteditable events, formatting commands, and selection management) are handled in the JS/TypeScript bridge.

Notes

To use this component, you need to install the
Bit.BlazorUI.Extras
nuget package, as described in the Optional steps of the Getting started page.

The content produced by the editor is untrusted input. Although the component strips obvious script vectors, you should still sanitize the emitted HTML on the server before storing or redisplaying it.

Usage

Basic

The simplest usage: a single tag gives you a fully functional editor with the default toolbar and a contenteditable surface.

Placeholder & height

Placeholder is shown while the editor is empty. Height sets the minimum height of the editing surface and accepts any CSS length (e.g. 300px, 20rem, or auto to grow with the content).

Readonly

Set ReadOnly to lock editing, which is handy for displaying stored content. Combine it with ShowToolbar set to false to hide the toolbar entirely and Height set to auto to fit the content.

Two-way binding

The content is a plain string you own. @bind-Value keeps it in sync both ways: edits flow out to your field, and programmatic changes (the buttons below) flow back into the editor without disturbing an in-progress caret when the value is unchanged.



Bound value:
<p>The bound value is just a <strong>string</strong> you own.</p>

Debounce

While typing, change notifications are debounced. Tune the window with DebounceMs (default 200). A larger value raises fewer change events; a smaller value updates the bound value more eagerly.


<p>Type and watch the value update after the debounce window.</p>

Focus & blur events

OnFocus and OnBlur fire when the editing surface gains or loses keyboard focus.


Editor is currently: blurred

Formatting

The default toolbar covers the everyday essentials: bold, italic, underline and strikethrough; paragraph and H1-H3 block formats; bullet and numbered lists; blockquote and code block; alignment; undo/redo; and clear formatting. Toolbar buttons light up to reflect the formatting at the cursor.

Indentation & scripts

The extended Indent and Script groups add increase/decrease indent and subscript/superscript. Combine toolbar flags to enable exactly the groups you need.

Toolbar groups

The Toolbar parameter is a Flags enum. Combine groups with bitwise OR to show only what you need - here just the inline and lists groups.

Full toolbar

Use the AllExtended preset to enable every available group, including images, tables, color, fonts, media, source view, find, full screen and more.

Links

Enable the Link group to insert, edit, and remove hyperlinks. Invalid or disallowed URLs raise OnError with a stable code such as invalid-url, and the content is left unchanged.

Images

Insert images by URL, drag-and-drop, or clipboard paste. Provide an OnImageUpload callback to persist the bytes and return a hosted URL, or return null to cancel. Without the callback, images are embedded as inline data URLs. Inserted images can be resized in place.

Colors

The Color group adds foreground (text) and background (highlight) color pickers. The active colors are reported back in the selection state so the toolbar can reflect them.

Fonts

The Font group adds family and size selectors. Provide your own options with FontFamilies and FontSizes, or leave them empty to use the built-in defaults.

Tables

The Table group inserts a table and, once the cursor is inside one, lets you add or remove rows and columns and merge cells. Column widths can be adjusted by dragging the cell borders.

Media & rules

The Media group embeds a direct audio/video URL as a native video/audio element. The Rule group inserts a horizontal divider. Note: iframe embeds (e.g. YouTube/Vimeo) are not kept by the default sanitization policy, so supply a custom policy that allows the iframe tag if you need such embeds.

Source view

The Source group toggles a raw HTML editor. On exit, the HTML is validated and run through the active sanitization policy before returning to the WYSIWYG surface.

Sanitization

Sanitization is allowlist-based: only the listed tags, attributes, and URI schemes are kept and everything else is stripped on paste, drag-drop, source-view exit, and programmatic changes. The browser pass is a first line of defense only - always sanitize the emitted HTML on the server too.

Plain-text paste

Set PasteAsPlainText to strip all formatting from pasted content and insert it as plain text.

Find & replace

The Find group adds a search panel that highlights matches and replaces them (single or all) over the editor content, with an optional case-sensitive toggle.

Full screen

The FullScreen group adds a toggle that expands the editor to fill the viewport for distraction-free writing, and collapses it back.

Slash menu

Type / at the start of a line to open a command menu for inserting headings, lists, quotes, and code blocks. Keep typing to filter the list, then press Enter. Markdown typing shortcuts (such as # for a heading) also work as you type.

Keyboard shortcuts

Common shortcuts work out of the box (Ctrl/Cmd+B for bold, Ctrl/Cmd+I for italic, and so on). Override or extend them with KeyboardShortcuts - a map of chords to command names. Use "ctrl" for the primary modifier on all platforms.

The command strings that can be mapped in KeyboardShortcuts are:
  • Inline: bold, italic, underline, strikeThrough
  • History: undo, redo
  • Lists: insertOrderedList, insertUnorderedList
  • Alignment: justifyLeft, justifyCenter, justifyRight, justifyFull
  • Indentation: indent, outdent
  • Script: subscript, superscript
  • Other: removeFormat, unlink, insertHorizontalRule

Emoji

The Emoji group adds a searchable picker for emoji and special characters.

Character & word count

Set ShowCount to display a count footer. Add MaxLength to cap the plain-text character count - input beyond the limit is prevented and the footer reflects the remaining budget.

0 words · 0/120 chars

EditForm validation

The editor participates in EditForm like any input. Bind a model property with @bind-Value and the component picks up the EditContext, so DataAnnotationsValidator and ValidationMessage work as expected.

0 words · 0/500 chars

Custom toolbar item

Add your own buttons with ToolbarConfig.CustomItems. Each item needs an Id and either an AriaLabel or a Label, plus an OnActivate callback that receives the editor instance - so it can call the imperative API. For display, supply a Label or an Icon. The custom "Today" button appears at the end of the toolbar below.

Reordering toolbar groups

Set ToolbarConfig.Order to a list of entry ids. Listed ids appear first in that order; any enabled-but-omitted groups are appended in their default order, and unknown ids are skipped.

Imperative API

Capture the component with @ref to drive it from code: FocusAsync moves keyboard focus, ExecuteCommandAsync runs a raw editing command, and GetHtmlAsync reads the current HTML.



result:

Style & Class

Use the Styles parameter to apply custom inline styles to individual parts of the editor (root, toolbar, group, button, editor, source, and count). The Classes parameter works the same way for CSS classes.

API

BitRichTextEditor parameters

Name Type Default value Description
Classes BitRichTextEditorClassStyles? null Custom CSS classes for different parts of the rich text editor.
DebounceMs int 200 Debounce window (ms) for content-change notifications while typing.
FontFamilies IReadOnlyList<string>? null Font families offered in the font-family selector. Null/empty uses defaults.
FontSizes IReadOnlyList<string>? null Font sizes offered in the font-size selector. Null/empty uses defaults.
Height string 300px Minimum height of the editing surface (any CSS length).
KeyboardShortcuts IReadOnlyDictionary<string, string>? null Custom key-combo to command map, merged over the built-in defaults.
Localizer IBitRichTextEditorLocalizer? null Localized labels/tooltips provider. Null uses built-in English labels.
MaxLength int? null Maximum plain-text character count. Null means unlimited.
OnBlur EventCallback Callback for when the editor loses focus.
OnChange EventCallback<string?> Callback for when the editor content changes.
OnError EventCallback<BitRichTextEditorError> Callback for when the editor encounters a recoverable error.
OnFocus EventCallback Callback for when the editor gains focus.
OnImageUpload Func<BitRichTextEditorImageUpload, Task<string?>>? null Invoked to persist an image binary, returning the URL to embed. When null, dropped or pasted images are embedded as inline data URLs.
PasteAsPlainText bool false When true, pasted content is inserted as plain text.
Placeholder string? null The placeholder value of the editor shown while it is empty.
ReadOnly bool false Makes the editor readonly.
SanitizationPolicy BitRichTextEditorSanitizationPolicy? null Allowlist policy applied to all content. When null a secure default allowlist is applied.
ShowCount bool false Show the character/word count footer.
ShowToolbar bool true Whether the formatting toolbar is shown.
Styles BitRichTextEditorClassStyles? null Custom CSS styles for different parts of the rich text editor.
Toolbar BitRichTextEditorToolbar BitRichTextEditorToolbar.All Which toolbar groups to display.
ToolbarConfig BitRichTextEditorToolbarConfig? null Custom toolbar items and ordering. Null uses the default group order.
Value string? null The two-way bound HTML content of the editor.

BitRichTextEditor public members

Name Type Default value Description
FocusAsync ValueTask Moves keyboard focus into the editor.
GetHtmlAsync ValueTask<string> Returns the current HTML content of the editor.
ExecuteCommandAsync Task Runs a raw editing command against the editor.

BitComponentBase parameters

Name Type Default value Description
AriaLabel string? null Gets or sets the accessible label for the component, used by assistive technologies.
Class string? null Gets or sets the CSS class name(s) to apply to the rendered element.
Dir BitDir? null Gets or sets the text directionality for the component's content.
HtmlAttributes Dictionary<string, object> new Dictionary<string, object>() Captures additional HTML attributes to be applied to the rendered element, in addition to the component's parameters.
Id string? null Gets or sets the unique identifier for the component's root element.
IsEnabled bool true Gets or sets a value indicating whether the component is enabled and can respond to user interaction.
Style string? null Gets or sets the CSS style string to apply to the rendered element.
TabIndex string? null Gets or sets the tab order index for the component when navigating with the keyboard.
Visibility BitVisibility BitVisibility.Visible Gets or sets the visibility state (visible, hidden, or collapsed) of the component.

BitComponentBase public members

Name Type Default value Description
UniqueId Guid Guid.NewGuid() Gets the readonly unique identifier for the component's root element, assigned when the component instance is constructed.
RootElement ElementReference Gets the reference to the root HTML element associated with this component.

BitRichTextEditorClassStyles properties

Name Type Default value Description
Root string? null Custom CSS classes/styles for the root of the BitRichTextEditor.
Toolbar string? null Custom CSS classes/styles for the toolbar of the BitRichTextEditor.
Group string? null Custom CSS classes/styles for the toolbar groups of the BitRichTextEditor.
Button string? null Custom CSS classes/styles for the toolbar buttons of the BitRichTextEditor.
Editor string? null Custom CSS classes/styles for the editor (content) area of the BitRichTextEditor.
Source string? null Custom CSS classes/styles for the HTML source view textarea of the BitRichTextEditor.
Count string? null Custom CSS classes/styles for the character/word count footer of the BitRichTextEditor.

BitRichTextEditorToolbarConfig properties

Configures toolbar ordering and custom items.

Name Type Default value Description
Order IReadOnlyList<string>? null Explicit ordering of toolbar entry ids (built-in group ids and custom item ids).
CustomItems IReadOnlyList<BitRichTextEditorToolbarItem>? null Custom toolbar items (max 50 are rendered).

BitRichTextEditorToolbarItem properties

A custom toolbar button supplied by the host.

Name Type Default value Description
Id string Unique id used for ordering and lookup.
Label string? null Text label shown when no icon is provided.
Icon RenderFragment? null Optional icon content.
AriaLabel string? null Optional accessible label / tooltip. When omitted, Label is used as the accessible name.
OnActivate Func<BitRichTextEditor, Task> Action invoked when the item is activated; receives the editor instance.

BitRichTextEditorImageUpload properties

An image to be persisted by the host's OnImageUpload delegate.

Name Type Default value Description
FileName string Original file name, when available.
ContentType string MIME type, e.g. "image/png".
Content byte[] Raw image bytes.

BitRichTextEditorError properties

An error surfaced by the editor (e.g. invalid URL, failed upload, invalid HTML).

Name Type Default value Description
Code string Stable error code, e.g. "invalid-url".
Message string Human-readable description.

BitRichTextEditorToolbar enum

Name Value Description
None 0
History 1
BlockFormat 2
Inline 4
Lists 8
Blocks 16
Link 32
Alignment 64
Clear 128
Image 256
Color 512
Font 1024
Indent 2048
Script 4096
Source 8192
Table 16384
Media 32768
Rule 65536
Emoji 131072
Find 262144
FullScreen 524288
Direction 1048576
All 255
AllExtended 2097151

BitVisibility enum

Name Value Description
Visible 0 The content of the component is visible.
Hidden 1 The content of the component is hidden, but the space it takes on the page remains (visibility:hidden).
Collapsed 2 The component is hidden (display:none).

BitDir enum

Name Value Description
Ltr 0 Ltr (left to right) is to be used for languages that are written from the left to the right (like English).
Rtl 1 Rtl (right to left) is to be used for languages that are written from the right to the left (like Arabic).
Auto 2 Auto lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element.

Feedback

You can give us your feedback through our GitHub repo by filing a new Issue or starting a new Discussion.


Or you can review / edit this page on GitHub.


Or you can review / edit this component on GitHub.

  • On this page