Skip to content

API reference ​

This page describes the public surface of @erag/text-editor-react. The examples use React 18/19 function components, TypeScript, and the package's published types.

Runtime exports ​

ts
import {
    Editor,
    defaultEditorConfig,
    sanitizeHtml,
} from '@erag/text-editor-react';
ExportPurpose
EditorThe React component used to render the editor. It forwards a ref to an EditorInstance.
defaultEditorConfigThe resolved default configuration. Treat it as read-only; pass your overrides through init.
sanitizeHtml(html, options)Sanitizes an HTML string using explicit allowedTags, allowedAttributes, and allowRelativeUrls options. It returns an empty string when browser DOM APIs are unavailable; sanitize untrusted HTML on the server as well.

Most consumers should configure init.sanitize and let Editor call the sanitizer. The direct utility is useful when preparing a browser-side preview with the same allowlist.

ts
const safeHtml = sanitizeHtml('<p>Hello</p><script>alert(1)</script>', {
    allowedTags: ['p'],
    allowedAttributes: {},
    allowRelativeUrls: true,
});

Props (EditorProps) ​

PropTypeDefaultDescription
valuestring—Controlled HTML. Pair it with onChange to keep your state in sync.
defaultValuestring''Initial HTML for uncontrolled usage. Ignored when value is provided.
initEditorInitpackage defaultsPartial editor configuration. Changes are detected structurally (functions are ignored), so inline objects are fine. It is never mutated.
disabledbooleanfalseDisables editing and editor actions.
readOnlybooleanfalsePrevents content changes while keeping safe viewing actions available.
idstring—Applied to the editable content element.
namestring—Adds a hidden form input containing the current HTML, so native form posts include it.
ariaLabelstring'Rich text editor'Accessible label for the editing surface.
classNamestring—Extra class names added to the outer .erag-editor shell.
tsx
<Editor
    id="message-body"
    value={content}
    onChange={setContent}
    name="body"
    ariaLabel="Message body"
    init={editorConfig}
    disabled={isDisabled}
    className="my-editor"
/>

Callback props (EditorEvents) ​

CallbackPayloadWhen it is called
onChangestringHTML actually changed. Duplicate values are not reported.
onClickMouseEventThe editable area is clicked.
onFocusFocusEventThe editable area receives focus.
onBlurFocusEventThe editable area loses focus.
onInputInputEventA native editor input is handled.
onCommitstringOn blur, when HTML changed since the previous committed value.
onKeyDownKeyboardEventA key is pressed in the editor.
onPasteClipboardEventA paste action is handled.
onReadyHTMLElementThe editable root is connected on the client.
onSelectionChangeSelectionThe browser selection changes while the editor is active.
onResize{ height: number }The bottom resize handle changes editor height.
onMentionSearchMentionSearchEventA debounced mention search starts.
onMentionSelectMentionSelectEventA mention is inserted.
onMentionRemoveMentionRemoveEventA complete mention token is removed.
onMergeTagSelectMergeTagSelectEventA merge tag is inserted.
onMergeTagRemoveMergeTagRemoveEventA complete merge-tag token is removed.
onTemplateInsertTemplateInsertEventA configured template is inserted.
onImageRemoveImageDeleteInfoAn image is removed after any configured delete handler succeeds.

DOM event payloads are native browser events (MouseEvent, FocusEvent, and so on), not React synthetic events.

tsx
<Editor
    value={content}
    onChange={setContent}
    onReady={handleReady}
    onCommit={saveDraft}
    onResize={({ height }) => console.log(height)}
    onImageRemove={handleImageRemove}
/>

Instance methods (EditorInstance) ​

Pass a typed ref when another control needs to call the editor directly.

tsx
import { useRef } from 'react';
import { Editor, type EditorInstance } from '@erag/text-editor-react';

export default function Composer() {
    const editor = useRef<EditorInstance>(null);

    function insertGreeting(): void {
        editor.current?.focus();
        editor.current?.insertText('Hello ');
    }

    return (
        <>
            <button type="button" onClick={insertGreeting}>
                Insert greeting
            </button>
            <Editor ref={editor} />
        </>
    );
}
MethodResultDescription
focus()voidFocuses the editable area.
blur()voidRemoves focus from it.
getHtml()stringReturns current normalized HTML.
setHtml(value)voidReplaces content and publishes the change.
getText()stringReturns plain text.
clear()voidReplaces content with an empty string.
insertHtml(value)voidSanitizes and inserts HTML at the saved selection.
insertText(value)voidEscapes and inserts plain text.
selectAll()voidSelects the editor content.
undo() / redo()voidMoves through editor history when possible.
openSourceCode()voidOpens the source-code dialog.
openPreview()voidOpens the preview dialog.
getRootElement()HTMLElement | nullReturns the editable root, not the outer editor shell.

Render props (EditorSlots) ​

Custom UI is passed as ReactNode props or render functions.

PropTypePurpose
toolbarStartReactNodeContent before toolbar groups.
toolbarEndReactNodeContent after toolbar groups.
menubarEndReactNodeContent at the end of the menubar.
statusbarStartReactNodeContent before the status information.
statusbarEndReactNodeContent after the status information.
emptyStateReactNodeCustom empty-state content inside the editable canvas.
renderMentionItem({ item, active }) => ReactNodeCustom mention result rendering.
renderMentionLoading({ query }) => ReactNodeCustom mention loading state.
renderMentionEmpty({ query }) => ReactNodeCustom mention empty state.
renderMentionError({ query, retry }) => ReactNodeCustom mention error state.
tsx
<Editor
    value={content}
    onChange={setContent}
    toolbarEnd={<span className="toolbar-hint">Draft</span>}
    renderMentionItem={({ item, active }) => (
        <span className={active ? 'is-active' : undefined}>{item.label}</span>
    )}
/>

Render props add presentation only; editor keyboard handling and selection management remain internal.

Released under the MIT License. Copyright © Er Amit Gupta