groupdocs-free-consulting / projects

0 stars 0 forks source link

GroupDocs.Viewer - Show rendered html in react #50

Open haseebmukhtar opened 5 days ago

haseebmukhtar commented 5 days ago

Hi

We are trying to view documents online on our react application.

We want to use .Net6 on backend to render the documents in HTML and show HTML in frontend (react application) Using GroupDocs.Viewer on .Net6, we can get the response from "viewer-api/loadDocumentDescription" API endpoint but the html is showing as a simple text.

How can we show rendered HTML properly on react application (frontend).

vladimir-litvinchik commented 5 days ago

@haseebmukhtar

Sure, in case you want to display raw HTML you can use dangerouslySetInnerHTML. Learn more at https://react.dev/reference/react-dom/components/common.

The following example demonstrates how it can be done in sample React application:

  1. Create the app npx create-react-app my-api-app
  2. Navigate to the created folder with cd my-api-app
  3. Replace code in App.js with
    
    import React, { useState } from 'react';

function App() { const [pageHtml, setPageHtml] = useState(null); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null);

const handleClick = async () => { setIsLoading(true); setError(null);

try {
  const response = await fetch('http://localhost:8080/viewer/loadDocumentDescription', {
    method: 'POST', // Change to POST method
    headers: { 'Content-Type': 'application/json' }, // Set content type header
    body: JSON.stringify({ guid: 'sample.docx' }), // Add request body with data
  });
  const data = await response.json();
  const html = data.pages[0].data;
  setPageHtml(html);
} catch (error) {
  setError(error.message);
} finally {
  setIsLoading(false);
}

};

return (

{isLoading &&

Loading...

} {error &&

Error: {error}

} {pageHtml && (
)}

); }

export default App;


4. Run the app with `npm start`
5. Unpack [self-host-api.zip](https://github.com/user-attachments/files/16113933/self-host-api.zip) and start it with `dotnet run`
6. In web browser click `Load page` button to retrieve and display a page.

<img width="601" alt="react-app" src="https://github.com/groupdocs-free-consulting/projects/assets/35294201/5c99f632-a718-4671-96eb-96121761ade0">

The React application: [my-react-app.zip](https://github.com/user-attachments/files/16113944/my-react-app.zip).

Hope it helps.