### Install Serve Package
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Install the 'serve' package globally to create a static server for production deployment.
```bash
npm install -g serve
```
--------------------------------
### Start Development Server
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Run the React development server to test the application locally.
```bash
npm run start
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Install the necessary project dependencies for the ONLYOFFICE Document Editor React component. This command should be run after cloning the repository.
```bash
npm install
```
--------------------------------
### Install ONLYOFFICE Document Editor React Component
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Install the ONLYOFFICE Document Editor React component from npm and save it to package.json.
```bash
npm install --save @onlyoffice/document-editor-react
```
--------------------------------
### Initialize DocumentEditor Component
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Basic setup for the DocumentEditor component, including required props and event handlers for document readiness and errors. Ensure the documentServerUrl is correct and the config object is properly structured.
```tsx
import React from "react";
import { DocumentEditor } from "@onlyoffice/document-editor-react";
export default function App() {
const handleDocumentReady = (event: object) => {
console.log("Document is ready:", event);
};
const handleError = (errorCode: number, errorDescription: string) => {
console.error(`Editor error [${errorCode}]: ${errorDescription}`);
// errorCode -1 → unknown error
// errorCode -2 → failed to load DocsAPI from documentServerUrl
// errorCode -3 → DocsAPI loaded but not defined on window
};
return (
);
}
```
--------------------------------
### Start Storybook for ONLYOFFICE Document Editor React
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Start the Storybook development server for the ONLYOFFICE Document Editor React component. This allows for interactive development and testing of UI components.
```bash
npm run storybook
```
--------------------------------
### Dynamically Change Document Server URL
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Example of how to dynamically switch the `documentServerUrl` prop at runtime. Changing this prop will cause the current editor instance to be destroyed and a new one to be initialized with the updated server address.
```tsx
// Switching between staging and production servers at runtime
const [env, setEnv] = React.useState<"staging" | "prod">("prod");
const serverUrl = env === "prod"
? "https://docs.mycompany.com/"
: "https://docs-staging.mycompany.com/";
```
--------------------------------
### Serve Project Folder
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Serve the project folder directly using the 'serve' command.
```bash
cd onlyoffice-react-demo
serve
```
--------------------------------
### Create React App
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Use Create React App to scaffold a new React project.
```bash
npx create-react-app onlyoffice-react-demo
```
--------------------------------
### Navigate to Project Directory
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Change the current directory to the newly created React project.
```bash
cd onlyoffice-react-demo
```
--------------------------------
### Build React Application for Production
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Create a production build of the React application. This will generate a 'build' directory.
```bash
npm run build
```
--------------------------------
### Serve Static Site
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Serve the built static site on port 3000. The port can be adjusted using the -l or --listen flags.
```bash
serve -s build
```
```bash
serve -s build -l 4000
```
--------------------------------
### Handle Editor Lifecycle Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Use `events_onAppReady`, `events_onDocumentReady`, and `events_onDocumentStateChange` to respond to editor initialization, document loading, and changes in document save state.
```tsx
import React, { useRef } from "react";
import { DocumentEditor } from "@onlyoffice/document-editor-react";
export default function EditorWithLifecycle() {
const editorInstanceRef = useRef(null);
const [isDirty, setIsDirty] = React.useState(false);
const onAppReady = (instance: object) => {
editorInstanceRef.current = instance;
console.log("Editor app ready. Instance:", instance);
};
const onDocumentReady = (event: object) => {
console.log("Document fully loaded and editable.", event);
};
const onDocumentStateChange = (event: any) => {
// event.data === true when there are unsaved changes
setIsDirty(event.data);
console.log("Unsaved changes:", event.data);
};
return (
<>
{isDirty &&
Unsaved changes!
}
>
);
}
```
--------------------------------
### Create Package for ONLYOFFICE Document Editor React
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Create a package (e.g., .tgz file) of the ONLYOFFICE Document Editor React component. This is useful for local testing or distribution.
```bash
npm pack
```
--------------------------------
### Build Storybook for ONLYOFFICE Document Editor React
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Build the Storybook for the ONLYOFFICE Document Editor React component. This command generates a static version of the Storybook for deployment.
```bash
npm run build-storybook
```
--------------------------------
### Configure Load Balancer Affinity with `shardkey`
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Control load balancer routing for document editing sessions. Use `true` for default behavior (document key), a string for custom keys (e.g., tenant ID), or `false` to disable.
```tsx
// Use document key as shard key (default behaviour)
```
```tsx
// Use a custom shard key (e.g., tenant ID)
```
```tsx
// Disable shardkey entirely
```
--------------------------------
### Configure Read-Only Viewer in React
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Use the `IConfig` interface to set up a read-only viewer. Ensure `edit`, `comment`, `copy`, and `review` permissions are set to `false` for viewing.
```tsx
import { IConfig } from "@onlyoffice/document-editor-react";
// Read-only viewer configuration
const viewerConfig: IConfig = {
documentType: "word",
document: {
fileType: "docx",
key: "readonly-doc-v1",
title: "Read Only Document.docx",
url: "https://example.com/readonly.docx",
permissions: {
edit: false,
comment: false,
download: true,
print: true,
copy: false,
review: false,
fillForms: false,
},
},
editorConfig: {
mode: "view",
lang: "en",
customization: {
compactHeader: true,
compactToolbar: true,
help: false,
},
},
};
```
--------------------------------
### Multiple Document Editors on One Page
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Demonstrates how to render multiple independent DocumentEditor instances on the same page by assigning a unique `id` to each component. This ensures proper instance management within the ONLYOFFICE editor framework.
```tsx
// Two independent editors on one page
<>
>
```
--------------------------------
### Build ONLYOFFICE Document Editor React Project
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Build the ONLYOFFICE Document Editor React project using Rollup. This command compiles the source code into a distributable format.
```bash
npm run rollup
```
--------------------------------
### Handle Insert Image and Save As Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Implement custom workflows for inserting images and saving documents. Your application must open file pickers and use the editor instance API to pass results back.
```tsx
{
const { c } = event.data; // "change" or "add"
openImagePicker().then((images) => {
window.DocEditor.instances["insertEditor"].insertImage({ c, images });
});
}}
events_onRequestSaveAs={(event: any) => {
const { fileType, title, url } = event.data;
console.log(`Save As requested: ${title}.${fileType} from ${url}`);
downloadAndSave(url, `${title}.${fileType}`);
}}
events_onRequestSelectDocument={(event: any) => {
// For document comparison (replaces deprecated onRequestCompareFile)
openDocumentPicker().then((doc) => {
window.DocEditor.instances["insertEditor"].setRequestedDocument({ c: event.data.c, ...doc });
});
}}
events_onRequestSelectSpreadsheet={(event: any) => {
// For mail merge recipients (replaces deprecated onRequestMailMergeRecipients)
openSpreadsheetPicker().then((spreadsheet) => {
window.DocEditor.instances["insertEditor"].setRequestedSpreadsheet({ c: event.data.c, ...spreadsheet });
});
}}
/>
```
--------------------------------
### Clone ONLYOFFICE Document Editor React Project
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Clone the ONLYOFFICE Document Editor React project from GitHub. This is the first step to set up the project for local development.
```bash
git clone https://github.com/ONLYOFFICE/document-editor-react
```
--------------------------------
### Basic React Document Editor Integration
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Render a basic document editor in your React app by providing the `documentServerUrl` and a `config` object. Includes error handling and a document ready event.
```tsx
// src/App.tsx — minimal complete integration
import React from "react";
import { DocumentEditor } from "@onlyoffice/document-editor-react";
export default function App() {
return (
);
}
```
--------------------------------
### Configure Document Editor in App.js
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Integrate the DocumentEditor component into your React application. Ensure to replace placeholder URLs with your actual server and file URLs. The callbackUrl is essential for saving functionality.
```javascript
import React, { useRef } from 'react';
import { DocumentEditor } from "@onlyoffice/document-editor-react";
var onDocumentReady = function (event) {
console.log("Document is loaded");
};
var onLoadComponentError = function (errorCode, errorDescription) {
switch(errorCode) {
case -1: // Unknown error loading component
console.log(errorDescription);
break;
case -2: // Error load DocsAPI from http://documentserver/
console.log(errorDescription);
break;
case -3: // DocsAPI is not defined
console.log(errorDescription);
break;
}
};
export default function App() {
return (
<>
>
);
}
```
--------------------------------
### Insert Image & Save As Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Callbacks for handling image insertion and save-as workflows initiated by the user.
```APIDOC
## Insert Image & Save As Events
### Description
Callbacks invoked when the user triggers insert-image or save-as workflows inside the editor. Your application is responsible for opening a file picker and passing the result back via the editor instance API.
### events_onRequestInsertImage
#### Description
Called when the user triggers the insert-image workflow.
#### Parameters
- **event** (any) - The event object containing context (`c`) for 'change' or 'add' in `event.data`.
### events_onRequestSaveAs
#### Description
Called when the user triggers the save-as workflow.
#### Parameters
- **event** (any) - The event object containing file type, title, and URL in `event.data`.
### events_onRequestSelectDocument
#### Description
Called for document comparison (replaces deprecated `onRequestCompareFile`).
#### Parameters
- **event** (any) - The event object containing context (`c`) in `event.data`.
### events_onRequestSelectSpreadsheet
#### Description
Called for mail merge recipients (replaces deprecated `onRequestMailMergeRecipients`).
#### Parameters
- **event** (any) - The event object containing context (`c`) in `event.data`.
### Request Example
```tsx
{
const { c } = event.data; // "change" or "add"
openImagePicker().then((images) => {
window.DocEditor.instances["insertEditor"].insertImage({ c, images });
});
}}
events_onRequestSaveAs={(event: any) => {
const { fileType, title, url } = event.data;
console.log(`Save As requested: ${title}.${fileType} from ${url}`);
downloadAndSave(url, `${title}.${fileType}`);
}}
events_onRequestSelectDocument={(event: any) => {
// For document comparison (replaces deprecated onRequestCompareFile)
openDocumentPicker().then((doc) => {
window.DocEditor.instances["insertEditor"].setRequestedDocument({ c: event.data.c, ...doc });
});
}}
events_onRequestSelectSpreadsheet={(event: any) => {
// For mail merge recipients (replaces deprecated onRequestMailMergeRecipients)
openSpreadsheetPicker().then((spreadsheet) => {
window.DocEditor.instances["insertEditor"].setRequestedSpreadsheet({ c: event.data.c, ...spreadsheet });
});
}}
/>
```
```
--------------------------------
### Test ONLYOFFICE Document Editor React Component
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Run tests for the ONLYOFFICE Document Editor React component. This command executes the test suite to ensure the component's functionality.
```bash
npm run test
```
--------------------------------
### Full ONLYOFFICE Configuration Object (`IConfig`)
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Provide comprehensive editor settings using the `IConfig` object. This object maps to the ONLYOFFICE Config API and controls document properties, permissions, UI, and more. The component deep-clones this object, so mutations after render do not affect the running editor.
```tsx
import { DocumentEditor, IConfig } from "@onlyoffice/document-editor-react";
const config: IConfig = {
documentType: "word",
height: "100%",
width: "100%",
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // JWT for secure mode
document: {
fileType: "docx",
key: "doc-key-2024-v3",
title: "Annual Report.docx",
url: "https://example.com/files/annual-report.docx",
info: {
owner: "John Smith",
uploaded: "2024-01-15",
favorite: false,
},
permissions: {
edit: true,
comment: true,
download: true,
print: true,
review: true,
copy: true,
fillForms: true,
modifyFilter: false,
},
},
editorConfig: {
callbackUrl: "https://example.com/api/documents/callback",
lang: "en",
region: "en-US",
mode: "edit", // "edit" | "view"
user: {
id: "user-123",
name: "Jane Doe",
group: "editors",
},
coEditing: {
mode: "fast", // "fast" | "strict"
change: true,
},
customization: {
autosave: true,
forcesave: false,
compactHeader: false,
compactToolbar: false,
uiTheme: "theme-dark",
zoom: 100,
review: {
trackChanges: false,
showReviewChanges: false,
reviewDisplay: "original",
},
},
},
};
```
--------------------------------
### Configure Document Server URL
Source: https://github.com/onlyoffice/document-editor-react/blob/master/README.md
Update the document server address in the config file. This is necessary for the component to connect to the ONLYOFFICE Document Server.
```json
"documentServerUrl": "http://documentserver/"
```
--------------------------------
### Handle Editor Initialization Errors
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
The `onLoadComponentError` callback is invoked when the component fails to initialize. It receives an error code and description. If omitted, errors are logged to the console.
```tsx
const handleLoadError = (errorCode: number, errorDescription: string) => {
switch (errorCode) {
case -1:
alert("An unexpected error occurred while loading the editor.");
break;
case -2:
alert(`Could not reach Document Server. Check the URL and network.\n${errorDescription}`);
break;
case -3:
alert("Document Server API loaded but is not functional. Verify server health.");
break;
}
};
```
--------------------------------
### Control Editor Size and Platform Mode
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Use `height`, `width`, and `type` props to control the editor's rendered size and platform mode. `height` and `width` accept CSS dimension strings, while `type` can be 'desktop' or 'mobile'.
```tsx
// Responsive mobile editor
```
--------------------------------
### Manage Collaboration and History Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Integrate with your application's sharing, renaming, and version history features. Each callback receives an event object and must use `window.DocEditor.instances[id]` to complete the action.
```tsx
{
openShareModal().then((sharingSettings) => {
window.DocEditor.instances["collabEditor"].setSharingSettings({ sharingSettings });
});
}}
// Called when user requests a document rename
events_onRequestRename={(event: any) => {
const newTitle = event.data;
renameDocumentOnServer(newTitle).then(() => {
console.log("Renamed to:", newTitle);
});
}}
// Called when version history panel is opened
events_onRequestHistory={(event) => {
fetchVersionHistory().then((history) => {
window.DocEditor.instances["collabEditor"].refreshHistory({ currentVersion: 3, history });
});
}}
// Called when a specific history version is selected
events_onRequestHistoryData={(event: any) => {
const version = event.data;
fetchVersionData(version).then((data) => {
window.DocEditor.instances["collabEditor"].setHistoryData(data);
});
}}
// Called when user lookup is needed (e.g., for @mentions)
events_onRequestUsers={(event: any) => {
const { c, id } = event.data;
searchUsers(id).then((users) => {
window.DocEditor.instances["collabEditor"].setUsers({ c, users });
});
}}
// Called when "Edit" button is clicked in view mode
events_onRequestEditRights={(event) => {
checkEditPermission().then((allowed) => {
if (allowed) window.DocEditor.instances["collabEditor"].applyEditRights();
});
}}
/>
```
--------------------------------
### Handle Editor Error, Warning, and Info Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Use these event handlers to monitor the editor's status. `events_onError` is for critical errors, `events_onWarning` for non-fatal issues, and `events_onInfo` for informational messages. Ensure your error tracking service is configured to capture relevant data.
```tsx
{
console.error("Editor error:", event.data);
// Send to your error tracking service
myErrorTracker.capture({ source: "onlyoffice", ...event.data });
}}
events_onWarning={(event: any) => {
console.warn("Editor warning:", event.data);
}}
events_onInfo={(event: any) => {
console.info("Editor info:", event.data);
}}
/>
```
--------------------------------
### Configure Embedded Editor in React
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Set up an embedded or kiosk mode editor using `IConfig`. The `type: "embedded"` option and specific `editorConfig.embedded` properties are crucial for this mode.
```tsx
import { IConfig } from "@onlyoffice/document-editor-react";
// Embedded / kiosk configuration
const embeddedConfig: IConfig = {
documentType: "word",
type: "embedded",
document: {
fileType: "docx",
key: "embed-doc-v1",
title: "Embedded.docx",
url: "https://example.com/embed.docx",
},
editorConfig: {
embedded: {
embedUrl: "https://example.com/embed/docx",
fullscreenUrl: "https://example.com/view/docx",
saveUrl: "https://example.com/download/docx",
shareUrl: "https://example.com/share/docx",
toolbarDocked: "top",
},
},
};
```
--------------------------------
### Error and Warning Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Handles runtime errors, non-fatal issues, and informational messages from the editor.
```APIDOC
## events_onError, events_onWarning, events_onInfo
### Description
Runtime events emitted by the ONLYOFFICE editor itself. `events_onError` fires on editor-level errors (e.g., co-editing conflicts). `events_onWarning` fires on non-fatal issues. `events_onInfo` delivers informational messages about editor state.
### Parameters
- **event** (any) - The event object containing data about the error, warning, or info.
### Request Example
```tsx
{
console.error("Editor error:", event.data);
// Send to your error tracking service
myErrorTracker.capture({ source: "onlyoffice", ...event.data });
}}
events_onWarning={(event: any) => {
console.warn("Editor warning:", event.data);
}}
events_onInfo={(event: any) => {
console.info("Editor info:", event.data);
}}
/>
```
```
--------------------------------
### Set Editor Interface Language
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
The `editorConfig_lang` prop sets the editor's interface language using BCP 47 codes. This overrides `config.editorConfig.lang`. Supported languages include 'en', 'fr', 'de', 'es', 'pt', 'ru', 'zh', 'ja', 'ko', 'ar', and more.
```tsx
const [lang, setLang] = React.useState("en");
<>
>
```
--------------------------------
### Collaboration & History Events
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Enables integration with sharing, renaming, version history, and user lookup functionalities.
```APIDOC
## Collaboration & History Events
### Description
A set of event props enabling deep integration with your application's sharing, rename, version history, and user-lookup flows. Each callback receives an event object from ONLYOFFICE and is expected to call back into the editor via the `window.DocEditor.instances[id]` API to complete the action.
### events_onRequestSharingSettings
#### Description
Called when user clicks the "Share" button.
#### Parameters
- **event** (any) - The event object.
### events_onRequestRename
#### Description
Called when user requests a document rename.
#### Parameters
- **event** (any) - The event object containing the new title in `event.data`.
### events_onRequestHistory
#### Description
Called when version history panel is opened.
#### Parameters
- **event** (any) - The event object.
### events_onRequestHistoryData
#### Description
Called when a specific history version is selected.
#### Parameters
- **event** (any) - The event object containing the selected version in `event.data`.
### events_onRequestUsers
#### Description
Called when user lookup is needed (e.g., for @mentions).
#### Parameters
- **event** (any) - The event object containing context (`c`) and user ID (`id`) in `event.data`.
### events_onRequestEditRights
#### Description
Called when "Edit" button is clicked in view mode.
#### Parameters
- **event** (any) - The event object.
### Request Example
```tsx
{
openShareModal().then((sharingSettings) => {
window.DocEditor.instances["collabEditor"].setSharingSettings({ sharingSettings });
});
}}
events_onRequestRename={(event: any) => {
const newTitle = event.data;
renameDocumentOnServer(newTitle).then(() => {
console.log("Renamed to:", newTitle);
});
}}
events_onRequestHistory={(event) => {
fetchVersionHistory().then((history) => {
window.DocEditor.instances["collabEditor"].refreshHistory({ currentVersion: 3, history });
});
}}
events_onRequestHistoryData={(event: any) => {
const version = event.data;
fetchVersionData(version).then((data) => {
window.DocEditor.instances["collabEditor"].setHistoryData(data);
});
}}
events_onRequestUsers={(event: any) => {
const { c, id } = event.data;
searchUsers(id).then((users) => {
window.DocEditor.instances["collabEditor"].setUsers({ c, users });
});
}}
events_onRequestEditRights={(event) => {
checkEditPermission().then((allowed) => {
if (allowed) window.DocEditor.instances["collabEditor"].applyEditRights();
});
}}
/>
```
```
--------------------------------
### Set Document Type for Editor
Source: https://context7.com/onlyoffice/document-editor-react/llms.txt
Specify the document type using either the `documentType` prop or `config.documentType`. Supported types include 'word', 'cell', 'slide', 'pdf', and 'diagram'. The prop-level value overrides the config setting.
```tsx
// Word document (.docx, .odt, .txt, …)
```
```tsx
// Spreadsheet (.xlsx, .ods, .csv, …)
```
```tsx
// Presentation (.pptx, .odp, …)
```
```tsx
// Fillable PDF form
```
```tsx
// Diagram (.vsdx, …)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.