Ritext

EditorRef

Imperative methods available via the editor ref handle.

Attach a ref to the <Editor> component to access imperative methods for programmatic control of the editor.

Setup

"use client";
import { useRef } from 'react';
import { Editor, Toolbar, Content, type EditorRef } from 'ritext';

export default function MyEditor() {
  const ref = useRef<EditorRef>(null);

  return (
    <div>
      <Editor ref={ref} extensions={extensions}>
        <Toolbar />
        <Content />
      </Editor>
      <button onClick={() => ref.current?.clear()}>Clear</button>
    </div>
  );
}

Methods

Prop

Type

Examples

Insert content at cursor

ref.current?.insert('<strong>Hello, World!</strong>');

Insert at the end

ref.current?.insertAtEnd('<p>Appended paragraph</p>');

Replace selected text

// Replaces whatever the user has selected
ref.current?.replaceSelection('<em>Replacement text</em>');

Get HTML output

const html = ref.current?.getHTML();
console.log(html); // "<p>My content...</p>"

Set content programmatically

ref.current?.setContent('<h1>New Document</h1><p>Fresh content.</p>');

Clear the editor

ref.current?.clear();

Focus the editor

ref.current?.focus();

Access the Tiptap editor directly

For advanced use cases, access the underlying Tiptap Editor instance:

const tiptapEditor = ref.current?.editor;

if (tiptapEditor) {
  // Use any Tiptap command
  tiptapEditor.chain().focus().toggleBold().run();

  // Read state
  const isBold = tiptapEditor.isActive('bold');
  const wordCount = tiptapEditor.storage.characterCount?.words();
}

All ref methods are no-ops when the editor has not yet initialized (editor is null). Guard against this or use optional chaining: ref.current?.clear().

On this page