1

I have several react components from which i want to get a component as html string to send to server . lets say the component i want to send is <ReportComponent /> how it can be done. I tried

onRouteChanged = () => { console.log(<ReportComponent />); };

but this is not giving me as html.

Scenario is this

On click of a send button the currently viewing component on client machine should be send to the server to save as a report .

NIsham Mahsin
  • 340
  • 5
  • 18

3 Answers3

0

You could use plain document.querySelector and innerHTML property.

In ReportComponent add a wrapping div to render method and give it an id:

<div id="reportComponent">...important stuff that gets rendered...</div>

After ReportComponent is already rendered and in the DOM, you can do

const reportComponentHTML = document.querySelector("#reportComponent").innerHTML;
//send it to server or log it to console
console.log(reportComponentHTML)
  • this wont give me styles @Kristupas – NIsham Mahsin Feb 15 '19 at 06:51
  • You are asking for html specifically. However, your approach might be incorrect if you're trying so save some kind of report. Since you own html and css of report component, it would be correct to send only the data of the report to server and attach html and css on the server itself. – Kristupas Repečka Feb 15 '19 at 06:59
0

Try using renderToString() method

You need to use import {renderToString} from react-dom/server

Then log the component like

renderToString(<MyAwesomeComponent/>)

Make sure you pass the required props.

Anitta Paul
  • 455
  • 4
  • 15
  • i tried this but getting following error `Uncaught Invariant Violation: Could not find "store" in either the context or props of "Connect(InterpReport)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(InterpReport)".` – NIsham Mahsin Feb 15 '19 at 07:03
  • Are you using redux? – Anitta Paul Feb 15 '19 at 07:05
  • The component is not getting t he required props from the store. So as the error message says try passing the sore as a props inside the or the connect() method. – Anitta Paul Feb 15 '19 at 07:38
0

Assuming your problem is to get the complete HTML of rendered element. You have to ways to deal with either assign ID attribute or use refs attribute on the components and while calling onRouteChanged either fetch your component using getElementById or using refs in react.

For refs example you can refer How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

NOTE : refs might be depreciated in future release of react

Shadab Ahmed
  • 556
  • 9
  • 20