@docx-editor.dev/react

中文文档
2.37.0发布于 2026/11/11Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 51.7万

React DOCX editor adapter for the @docx-editor.dev editor contract.

原始使用文档
文档目录9 节
  1. Features
  2. Quick start
  3. Build your own UI
  4. Hooks
  5. Companion packages
  6. Which API for which job
  7. Documentation
  8. License
  9. Custom unsupported content

DOCX Editor by EigenPal

npm version npm downloads license Demo Documentation

@docx-editor.dev/react

A visual .docx editor for React. Open a DOCX document, edit its paginated layout, and save a DOCX file. Parsing and serialization run in the browser.

Saving preserves untouched content, unsupported OOXML, and package payloads. Continuous integration (CI) checks document structure and save-and-reopen behavior.

Install the adapter and its required engine peer:

npm install @docx-editor.dev/react @docx-editor.dev/core

Features

Quick start

Import the stylesheet once and give the editor a container with a defined height:

import { useState } from 'react';
import { DocxEditor } from '@docx-editor.dev/react';
import '@docx-editor.dev/core/styles/editor.css';

export function App() {
  const [doc, setDoc] = useState<Uint8Array>();

  return (
    <div style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}>
      <input
        type="file"
        accept=".docx"
        onChange={async (e) => {
          const file = e.target.files?.[0];
          setDoc(file ? new Uint8Array(await file.arrayBuffer()) : undefined);
        }}
      />
      <div style={{ flex: 1, minHeight: 0 }}>
        {doc && <DocxEditor document={doc} mode="edit" />}
      </div>
    </div>
  );
}

<DocxEditor> includes the title bar, menu, toolbar, navigation pane, context menu, and document pages. It fills its parent container.

For Next.js and server-side rendering (SSR), load the editor in the browser. Use dynamic(..., { ssr: false }) inside a Client Component.

Build your own UI

Use components and hooks to build your own controls. Packaged controls use the same public API.

import { DocxEditor, useEditorCommand } from '@docx-editor.dev/react';

function BoldButton() {
  const bold = useEditorCommand('text.bold');
  return (
    <button
      onMouseDown={(e) => e.preventDefault()} // chrome must not steal the caret
      onClick={() => bold.execute()}
      disabled={!bold.isEnabled}
      data-active={bold.isActive || undefined}
    >
      Bold
    </button>
  );
}

export function Editor({ bytes }: { bytes: Uint8Array }) {
  return (
    <DocxEditor.Root document={bytes}>
      <BoldButton />
      <DocxEditor.Viewport>
        <DocxEditor.Content />
      </DocxEditor.Viewport>
    </DocxEditor.Root>
  );
}

Root owns the editor instance. Viewport supplies scrolling, and Content displays pages. Add other controls as needed.

Use className, data-active, and icon for appearance changes. Use asChild to apply behavior to your own element. Use hidden or preset={false} to replace controls, or build controls with hooks.

Hooks

HookWhat it gives you
useEditorCommand(slot)execute, isActive, isEnabled, disabledReason
useEditorState(selector)A memoized slice of the editor snapshot
useDocxEditor()The editor instance, or null before mount
useEditorEvent(event, fn)change, selectionChange, error
useFontFamily() / useParagraphStyle()Value controls: current value, options, setter
usePageSetup()Margins, orientation, paper size
useDocumentOutline() / useDocumentSearch()The navigation pane, headless
useContentControl()Content controls at the caret

Read isEnabled to set the disabled state. Show disabledReason when the command is unavailable.

Companion packages

Which API for which job

Use the React or Vue adapter hooks, the review hooks, and DocxEditorReview from @docx-editor.dev/pro/react or @docx-editor.dev/pro/vue to build browser review controls. Use the editing API in @docx-editor.dev/editor-api for document automation. It follows the Office.js object model and runs in browser and server hosts.

TaskBrowser controls (React or Vue)Document automation
Comment on found texteditor.findMatches, editor.selectMatch, then useReview().commentbody.search, then Range.insertComment
Reply to a threaduseReview().reply(item, text)Comment.reply(text)
Record a tracked replacementSuggesting mode, then editor.exec({ type: 'replaceMatch', match, text })document.changeTrackingMode = 'TrackMineOnly', then Range.insertText(text, 'Replace')
Propose an AI rewrite as tracked changesprepareRewrite through DocxEditor.createBrowserprepareRewrite from @docx-editor.dev/editor-api/agent
Accept or reject a changeuseReview().accept(item) or useReview().reject(item)Revision.accept() or Revision.reject()
Open a change without scrollinguseReview().setActive(key, { reveal: false })Not applicable: no viewport
Highlight rangesuseHighlights(name, source, options)Not applicable
Custom review rail cardsDocxEditorReview with preset set to false, useStackedReviewPositions, and useReviewRailMetricsNot applicable
Comment-on-selection buttonDocxEditorReview.AddComment as a direct child of DocxEditorReview, or useEditorCommand('review.addComment')Not applicable
Page setup and paragraph dialogsDocxEditor.PageSetupDialog or DocxEditor.ParagraphDialogSection.pageSetup, and Paragraph properties such as alignment

This package ships the task recipes in docs/index.md. They are also on the site: Task recipes.

Documentation

License

Apache-2.0

Custom unsupported content

Register components under DocxEditor or DocxEditor.Root. Each declaration handles matching unsupported content, including opaque inline and block elements.

<DocxEditor document={bytes}>
  <DocxEditor.UnsupportedElement
    match={(element) => element.namespaceUri === 'urn:my-widgets'}
    layout={{ width: 180, height: 48 }}
  >
    {({ element }) => <MyWidget element={element} />}
  </DocxEditor.UnsupportedElement>
  <DocxEditor.UnsupportedElement>
    {({ element }) => <MyPlaceholder label={element.label} />}
  </DocxEditor.UnsupportedElement>
</DocxEditor>

The first mounted matching declaration wins. Prop updates retain its priority. Removing and mounting a declaration again gives it a later priority. To disable a specific renderer temporarily, keep it mounted and change match, or use matchers that do not overlap. Omit match for a catch-all. Use source metadata in predicates; geometry is not available before pagination. Return null to keep the default placeholder. An empty result does not select the next declaration.

UnsupportedElement exposes nodeId, ownerPartName, namespaceUri, localName, source, placement, and label. bounds describes the reserved box after layout. Optional drawing and equation records provide specialized metadata. Treat source content as read-only and untrusted.

layout reserves width and height in document points for opaque elements. Source placement determines inline or block flow. Without layout, opaque inline elements reserve 120 × 24 points; blocks reserve 240 × 96 points. Dimensions must be positive, finite, and at most 100,000 points. Drawing and equation fallbacks retain their existing geometry. Unmatched opaque content retains its existing invisible behavior. Properties, metadata, and nested payloads inside unsupported elements are not independent content occurrences.

Components retain framework context and local state across same-page repaints. They can remount when pagination, virtualization, or document changes remove an occurrence. Keep durable application data outside the component. Prop updates and declaration removal preserve document edits and undo history. Custom rendering does not change saved DOCX content.

版本与发布记录

@docx-editor.dev/react 共发布 64 个版本,首次发布于 2026/07/16;过去 12 个月发布了 64 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.37.0latest2026/11/112 天前
2.37.0-canary.20261111032756.sha-9eef508canary2026/11/112 天前
2.37.0-canary.20261110032710.sha-525df6f2026/11/103 天前
2.36.02026/11/094 天前
2.36.0-canary.20261108032737.sha-f189d652026/11/085 天前
2.35.1-canary.20261107032606.sha-f3116762026/11/076 天前

关于 @docx-editor.dev/react 的常见问题

@docx-editor.dev/react 是什么?

React DOCX editor adapter for the @docx-editor.dev editor contract.

如何安装 @docx-editor.dev/react?

在项目目录运行 npm install @docx-editor.dev/react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@docx-editor.dev/core(~2.37.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@docx-editor.dev/react 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@docx-editor.dev/react 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@docx-editor.dev/react 可以商用吗?

@docx-editor.dev/react 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@docx-editor.dev/react 的下载量有多少?

根据 npm 官方下载统计,@docx-editor.dev/react 在 2026/10/13 – 2026/11/11 这 30 天内被下载 516,920 次,日均约 17,231 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@docx-editor.dev/react 还在维护吗?

最新版本 2.37.0 发布于 2026/11/11(2 天前);至今共发布 64 个版本,其中过去 12 个月发布了 64 个;首次发布于 2026/07/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。