Crafting a Bespoke HTML Editor in React: Unlocking Seamless Content Creation

A rich-text editor in React has three separate jobs: provide a usable authoring interface, preserve meaningful document structure, and keep untrusted content from becoming executable code when it is saved or displayed. A WYSIWYG surface is not automatically a safe HTML renderer. The right architecture makes the trust boundary explicit before adding formatting buttons and editor plug-ins.

Choose a document representation before a component

A fictional knowledge-base editor needs headings, paragraphs, emphasis, lists and links, but not scripts or arbitrary CSS. Decide whether the canonical record is a structured editor document or restricted HTML. If it is a structured document, define a versioned serialization schema and conversion tests. If the application stores HTML, define an allowlist of elements and attributes the server will accept.

Keep an editor draft, the saved canonical record, and the read-only preview as distinct states. Copy-pasted content may include unsupported tags; a change in an editor library’s serializer can produce different HTML from the same visible document. Use round-trip tests before upgrading.

React rendering does not sanitize arbitrary HTML

React normally escapes text values rendered through its ordinary JSX expressions, but a WYSIWYG application may intentionally insert HTML. In particular, dangerouslySetInnerHTML is an escape hatch, not a sanitizer. The OWASP XSS Prevention Cheat Sheet cautions that rendering untrusted HTML requires appropriate sanitization, and that modifying supposedly sanitized output afterward can invalidate the safety decision.

Use a maintained, context-appropriate HTML sanitizer on the actual trust boundary, validate URL schemes for links and media, and restrict permissible editor features to what your product can render safely. Content Security Policy and Trusted Types can provide defense in depth, but should not replace the sanitizer.

Build a bounded, local React source-and-preview component

This minimal component makes the trust boundary visible. Authors edit an HTML string in a textarea. A separate sandboxed frame displays a preview. The host React tree never uses dangerouslySetInnerHTML, and the preview does not receive allow-scripts or allow-same-origin. The embedded policy restricts resource requests, while the character cap prevents accidental unlimited editing state. This is a local prototype only, not an HTML sanitizer or a complete collaborative editor.

import { useState } from "react";

const LIMIT = 20000;
const PREVIEW_POLICY = `<!doctype html>
<meta http-equiv="Content-Security-Policy"
  content="default-src 'none'; img-src data:; style-src 'unsafe-inline'">
<meta name="referrer" content="no-referrer">`;

export function LocalHtmlEditor() {
  const [markup, setMarkup] = useState("<h2>Sample heading</h2><p>Type HTML here.</p>");
  const overLimit = markup.length >= LIMIT;

  return (
    <section aria-label="Local HTML authoring preview">
      <label htmlFor="html-source">HTML source</label>
      <textarea
        id="html-source"
        rows={12}
        spellCheck={false}
        value={markup}
        onChange={(event) => setMarkup(event.target.value.slice(0, LIMIT))}
      />
      <p aria-live="polite">{markup.length} / {LIMIT} characters
        {overLimit ? " (limit reached)" : ""}</p>
      <iframe
        title="Isolated HTML preview"
        sandbox=""
        referrerPolicy="no-referrer"
        srcDoc={PREVIEW_POLICY + markup}
        style={{ width: "100%", minHeight: 240, border: "1px solid #ccc" }}
      />
    </section>
  );
}

Save this in a React project and render <LocalHtmlEditor />. Test ordinary headings, paragraphs and lists first. Then paste attempted event handlers, scripts, external image URLs and oversized text. Scripts should not execute in the isolated preview; external assets are constrained by its policy. Test the actual supported browsers. An application that allows user-authored content to be persisted or published must still sanitize and validate it on the server, enforce link scheme and media policies, and use server-side authorization. The isolated preview cannot replace those controls.

Before adding rich-text commands, make a second component for trusted, already sanitized saved content. Its output should be tested against the editor serializer and server allowlist. Do not silently assume that what looks correct in the local preview will survive a real save and reload.

Plan save, preview and conflict behavior

Each draft revision needs an identity, a last-saved timestamp or version token, and a clear outcome after a failed save. If another editor updated the same record, refuse a silent overwrite and show a merge or conflict decision. Autosave should debounce ordinary typing and handle network retries without creating duplicate versions.

A preview should render the same sanitized schema as the reader-facing page. If the preview accepts content the production renderer strips, authors will believe formatting was saved when it was not. Compare the two outputs with test fixtures.

Test abuse cases and ordinary editing together

Input or action Expected behavior
Pasted <script> or event-handler attributes Not executable in saved or previewed output
Link with a nonapproved URL scheme Rejected or converted to plain text
Long nested pasted content Bounded, valid output without browser freeze
Keyboard-only heading/list controls Controls can be reached and operated accessibly
Two editors save the same revision Version conflict is surfaced, not overwritten silently
Save fails after a timeout Draft remains recoverable and status is clear

Run the same fixtures through the editor, server validation, storage rehydration, export and read-only view. A single safe preview screenshot does not prove the stored round trip is safe.

Make vendor and accessibility choices based on requirements

An editor library may offer collaboration, image upload, custom nodes or markdown conversion. Choose only capabilities with a clear data model, maintenance path, licensing fit, and accessibility support. Test keyboard selection, screen-reader labels, link editing and mobile behavior with real users when possible. Avoid giving a browser editor direct access to file storage credentials or privileged server APIs.

Keep uploaded files in a separate validated pipeline with content-type checks, ownership, size limits and controlled publishing; rich text permissions should not implicitly authorize media publishing.

The quality of a React editor is measured by trustworthy round trips, controlled HTML rendering, recoverable saves and an accessible author experience. A growing toolbar is not evidence of those properties.

img