Write in Rara’s contenteditable notebook: beforeinput and the inputType of every keystroke, a paste kept as plain text, and where the caret goes when…
Every comment box, caption or note richer than a <textarea> meets contentEditable sooner or later. Knowing that its state is innerHTML, that beforeinput is the gate of every change, and that a paste carries HTML explains why the caret jumps in React, why plaintext-only is often the rescue, and why modern editors (Lexical, ProseMirror, TipTap) are built on beforeinput, not the obsolete document.execCommand.
A contentEditable editor’s state is its innerHTML, and beforeinput is its gate
innerHTML is bound from state (React) Writing innerHTML throws away the node the caret sits in. Set the HTML once (on mount, or a memoised dangerouslySetInnerHTML object), then only read innerHTML in the input handler into state. Do not re-render the content from that state.innerHTML to a database and rendering it raw That is an XSS path: markup from a paste or typing can carry <img onerror> or a javascript: link. Sanitise (DOMPurify) before saving and showing it, or save textContent if only the text is needed.plaintext-only works everywhere Older browsers treat that value as invalid, so the element cannot be typed in at all. Check first (el.contentEditable = 'plaintext-only' throws a SyntaxError where it is not supported), then keep a fallback: contenteditable="true" with a beforeinput handler that cancels insertFromPaste and puts getData('text/plain') in itself.beforeinput insertText, then input insertText, with the letter as data.Ctrl+B (mode true) The browser itself puts a <b> into the DOM, with inputType formatBold. You wrote no code for it.true Its tags come along: <b>, <span style>, <a>. That is a rich paste with no sanitising.plaintext-only (or paste as plain text), paste again Only the text comes in, without a single tag.