Mount SuperDoc in React
Open, edit, and export a DOCX from a React component with SuperDoc v2.
Use the stable superdoc@2 package in React. The component creates one Editor after its mount element exists, waits for
the document to open, and destroys the Editor when React unmounts it.
1. Create a React project
pnpm create vite@latest superdoc-react --template react-ts
cd superdoc-react
pnpm add superdoc@22. Prepare a document
Download the sample DOCX and save it as public/sample.docx:
Vite serves files in public from the root of the development server, so SuperDoc can load it from /sample.docx.
3. Create the Editor component
Replace src/App.tsx with this component:
import { useEffect, useRef, useState } from 'react';
import { SuperDoc } from 'superdoc';
import 'superdoc/style.css';
export default function App() {
const mountRef = useRef<HTMLDivElement>(null);
const superdocRef = useRef<SuperDoc | null>(null);
const mountedRef = useRef(false);
const [ready, setReady] = useState(false);
const [exporting, setExporting] = useState(false);
useEffect(() => {
if (!mountRef.current) return;
mountedRef.current = true;
const superdoc = new SuperDoc({
selector: mountRef.current,
document: '/sample.docx',
onReady: () => {
if (mountedRef.current) setReady(true);
},
onException: ({ error }) => {
console.error('SuperDoc could not open the document.', error);
},
});
superdocRef.current = superdoc;
return () => {
mountedRef.current = false;
superdocRef.current = null;
superdoc.destroy();
};
}, []);
async function exportDocument() {
const superdoc = superdocRef.current;
if (!superdoc) return;
setExporting(true);
try {
await superdoc.export({
exportType: ['docx'],
exportedName: 'sample-edited',
});
} catch (error) {
console.error('SuperDoc could not export the document.', error);
} finally {
if (mountedRef.current) {
setExporting(false);
}
}
}
return (
<main>
<button disabled={!ready || exporting} onClick={() => void exportDocument()} type='button'>
{exporting ? 'Exporting…' : 'Export DOCX'}
</button>
<div ref={mountRef} />
</main>
);
}
Remove the starter App.css import and replace the contents of src/index.css with:
html,
body,
#root {
min-height: 100%;
margin: 0;
}The mount effect runs once. onReady enables export only after the DOCX is open. The cleanup calls destroy() to
release Editor resources when React removes the component.
4. Edit and export
Run pnpm dev and open the printed URL. Replace a word in the document, then select Export DOCX. The browser should
download sample-edited.docx.
Add React-owned controls
The component above uses SuperDoc's built-in interface. When React should render your toolbar or panels, use the provider
and hooks from the superdoc/ui/react subpath. They bind to the same Editor instance and do not require another package.
Continue with React custom UI setup, or learn how to load and save user documents.