React examples
Load, save, compose, and automate documents with the React adapter.
These examples import public APIs from package roots.
Load DOCX bytes
This component fetches a DOCX file and passes its bytes to the editor:
import { useEffect, useState } from 'react';
import { DocxEditor } from '@docx-editor.dev/react';
export function Editor({ url }: { url: string }) {
const [doc, setDoc] = useState<Uint8Array>();
useEffect(() => {
let cancelled = false;
fetch(url)
.then((response) => response.arrayBuffer())
.then((buffer) => {
if (!cancelled) setDoc(new Uint8Array(buffer));
});
return () => {
cancelled = true;
};
}, [url]);
return <DocxEditor document={doc} title="Proposal.docx" />;
}Save through the ref
This component calls DocxEditorRef.save() and uploads the result:
import { useRef } from 'react';
import { DocxEditor, type DocxEditorRef } from '@docx-editor.dev/react';
export function SaveButton({ bytes }: { bytes: Uint8Array }) {
const ref = useRef<DocxEditorRef>(null);
async function save() {
const next = await ref.current?.save();
if (!next) return;
await fetch('/api/documents/42', { method: 'PUT', body: next });
}
return (
<>
<button onClick={() => void save()}>Save</button>
<DocxEditor ref={ref} document={bytes} />
</>
);
}Compose custom chrome
This example replaces the packaged frame with composition primitives.
The custom Bold button gets its state from useEditorCommand:
import { DocxEditor, useEditorCommand } from '@docx-editor.dev/react';
function BoldButton() {
const bold = useEditorCommand('text.bold');
return (
<button
// Prevent toolbar actions from moving the document caret.
onMouseDown={(event) => event.preventDefault()}
onClick={() => bold.execute()}
disabled={!bold.isEnabled}
>
Bold
</button>
);
}
export function CustomChrome({ bytes }: { bytes: Uint8Array }) {
return (
<DocxEditor.Root document={bytes}>
<DocxEditor.Toolbar>
<BoldButton />
</DocxEditor.Toolbar>
<DocxEditor.Viewport>
<DocxEditor.Navigation />
<DocxEditor.Content />
<DocxEditor.HyperLink />
<DocxEditor.ContextMenu />
</DocxEditor.Viewport>
</DocxEditor.Root>
);
}Automate an open editor
This component uses the Editing API to read the first paragraph. It disposes the browser runtime after the operation:
import { useDocxEditor } from '@docx-editor.dev/react';
import { DocxEditor as BrowserDocxEditor } from '@docx-editor.dev/editor-api/browser';
export function AutomateButton() {
const editor = useDocxEditor();
async function run() {
if (!editor) return;
const runtime = BrowserDocxEditor.createBrowser(editor);
try {
await runtime.run(async (context) => {
const first = context.document.body.paragraphs.getFirst();
first.load('text');
await context.sync();
});
} finally {
runtime.dispose();
}
}
return <button onClick={() => void run()}>Inspect first paragraph</button>;
}