Articles in this section

Which tools help you build a React DOCX Viewer with Document Editor?

Displaying and interacting with DOCX files directly within your React applications is efficiently achieved using the Syncfusion® React DOCX Editor component. Despite being called an “Editor,” it offers comprehensive capabilities for viewing, creating, and printing Word documents seamlessly in the browser. This article will identify which essential tools help you build a React DOCX Viewer using Syncfusion DOCX Editor and provide a step-by-step guide to integrate this powerful component.

Essential tools and their purpose

  • React (Version 15.5.4 or higher): JavaScript library for building your application’s user interface, providing component-based architecture for the viewer.
  • Node.js (Version 14.0.0 or above) & npm: Node.js serves as the JavaScript runtime for development, while npm manage project dependencies.
  • Syncfusion DOCX Editor: The primary UI component renders and displays DOCX content, handling layout, interaction, and styling with key viewing features.
  • Syncfusion DOCX Editor Backend Service (ASP.NET Core Web API): Converts .doc, .docx, .dotx, .rtf, and .txt files into the SFDT format required by the client-side Syncfusion DOCX editor.
    For detailed system requirements, refer to the documentation.

Step-by-Step guide to build a React DOCX viewer with Syncfusion

Step 1 : Create or use a React application

To load DOCX documents in React application, you first need an existing application or create a new React application. Refer to the documentation to create a new React application.

Step 2 : Install the Syncfusion® DOCX Editor package

All the Syncfusion® React component packages are available in npmjs.com public registry. To install the Document Editor component, use the following command

npm install @syncfusion/ej2-react-documenteditor --save 

Step 3: Add the required CSS styles

  • For the DOCX viewer to render correctly, you must import its stylesheet. The simplest way to do this is to add the import statement to your src/App.css file.
  • Open src/App.css and add the following lines at the top:
@import '../node_modules/@syncfusion/ej2-base/styles/material.css';
@import '../node_modules/@syncfusion/ej2-buttons/styles/material.css';
@import '../node_modules/@syncfusion/ej2-inputs/styles/material.css';
@import '../node_modules/@syncfusion/ej2-popups/styles/material.css';
@import '../node_modules/@syncfusion/ej2-lists/styles/material.css';
@import '../node_modules/@syncfusion/ej2-navigations/styles/material.css';
@import '../node_modules/@syncfusion/ej2-splitbuttons/styles/material.css';
@import '../node_modules/@syncfusion/ej2-dropdowns/styles/material.css';
@import "../node_modules/@syncfusion/ej2-documenteditor/styles/material.css";
@import "../node_modules/@syncfusion/ej2-ribbon/styles/material.css"; 

Step 4 : Add the DOCX Editor to a React Component

  • Now that the Syncfusion® DOCX Editor packages are installed and styles are imported, you can add the DOCX editor to your React application. You will typically replace the default content of your src/App.tsx with the DocumentEditorContainer component.

  • Open your src/App.tsx file and replace its content with the following code:

import React, { useRef, useEffect } from 'react';
import './App.css';
import { DocumentEditorContainerComponent, Ribbon } from '@syncfusion/ej2-react-documenteditor';
DocumentEditorContainerComponent.Inject(Ribbon);

function App() {
 const containerRef = useRef<DocumentEditorContainerComponent | null>(null);
 return (
   <div>
     <DocumentEditorContainerComponent
       id="container"
       ref={containerRef}
       height={'100vh'}
       toolbarMode="Ribbon"
     />
   </div>
 );
}

export default App; 

Step 5 : Add the license key

From v20.1.047 onwards, it is necessary to register a license key for Syncfusion® React components. For more information on obtaining and registering your license key, please refer to the documentation.

Step 6 : Initial client-side view

At this point, if you run your React application without a connected server, you will see the DOCX Editor’s UI, but it might not fully function until the serviceUrl points to a live backend. Open your terminal in the React project directory and run:

npm start 

Step 7: Web API for importing Word documents

As the Syncfusion® DOCX editor client-side script requires the document in SFDT file format, you can convert the Word documents (.dotx, .docx, .dot, .doc), rich text format documents (.rtf), and text documents (.txt) into SFDT format by using this Web API.

Create an ASP.NET Core Web API with the following example code for importing Word documents into the Document Editor component.

[AcceptVerbs("Post")]
       [HttpPost]
       [EnableCors("AllowAllOrigins")]
       [Route("Import")]
       public string Import(IFormCollection data)
       {
           if (data.Files.Count == 0)
               return null;
           Stream stream = new MemoryStream();
           IFormFile file = data.Files[0];
           int index = file.FileName.LastIndexOf('.');
           string type = index > -1 && index < file.FileName.Length - 1 ?
               file.FileName.Substring(index) : ".docx";
           file.CopyTo(stream);
           stream.Position = 0;

           //Hooks MetafileImageParsed event.
           WordDocument.MetafileImageParsed += OnMetafileImageParsed;
           WordDocument document = WordDocument.Load(stream, GetFormatType(type.ToLower()));
           //Unhooks MetafileImageParsed event.
           WordDocument.MetafileImageParsed -= OnMetafileImageParsed;

           string json = Newtonsoft.Json.JsonConvert.SerializeObject(document);
           document.Dispose();
           return json;
       } 

Refer and reuse the GitHub Web Service example or Docker image for hosting your own web service and use it for the serviceUrl property.

Step 8: Configure service URL and Load Document

Once your ASP.NET Core Web API service is running (e.g.,http://localhost:62869/api/documenteditor/), update the serviceUrl property in your src/App.tsx file to point to this URL. Then, add the following code snippet to load the document in the DOCX Editor.

import React, { useRef, useEffect } from 'react';
import './App.css';
import { DocumentEditorComponent, Ribbon } from '@syncfusion/ej2-react-documenteditor';
DocumentEditorComponent.Inject(Ribbon);

function App() {
 const containerRef = useRef<DocumentEditorComponent| null>(null);
 useEffect(() => {
   const container = containerRef.current;
   if (container) {
     const uploadDocument = new FormData();
     uploadDocument.append('DocumentName', 'Getting Started.docx');
     const loadDocumentUrl = container.serviceUrl + 'LoadDocument';
     const httpRequest = new XMLHttpRequest();
     httpRequest.open('POST', loadDocumentUrl, true);
     httpRequest.onreadystatechange = () => {
       if (httpRequest.readyState === 4) {
         if (httpRequest.status === 200 || httpRequest.status === 304) {
           if (container) {
             container.open(httpRequest.responseText);
           }
         }
       }
     };
     httpRequest.send(uploadDocument);
   }
 }, []);

 return (
   <div>
     <DocumentEditorComponent
             id="container"
             ref={containerRef}
             height={'90vh'}
             serviceUrl="http://localhost:62869/api/documenteditor/"
             isReadOnly={true}
         />
   </div>
 );
}

export default App; 

Step 9: Run the application

To see the Syncfusion ® DOCX viewer in action with a functioning backend, ensure your Web API service is running, then run your React application.

  • Start your Web API service
  • Run your React application: Open your terminal in the React project directory and run:
npm start 

Your browser will open to http://localhost:3000, where you will see the DOCX viewer displaying the Word document in a clean, read-only interface.

You can download a complete working sample of building a React DOCX Viewer from GitHub

Conclusion

I hope you enjoyed learning about which tools help you build a React DOCX Viewer with Document Editor.

You can refer to our React DOCX Editor feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our React DOCX Editor example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied