9

I need to send an email of my rendered reactjs component, for that, I need to convert my react component in HTML and send the email. I know how to send HTML through the mail, but getting stuck in how to get HTML from the reactjs component.

3 Answers 3

16

You can use renderToString of react-dom/server and use it like

import ReactDOMServer from 'react-dom/server'
const htmlString = ReactDOMServer.renderToString(<App />)

ReactDOMServer is used for SSR (Server Side Rendering) of react components.

renderToString converts your React component to string. So, You will get string html from JSX of your component.

5
  • 1
    Tried to console htmlString but it shows only <div></div>, the complete component is not printed, so am I doing something wrong? Commented Jul 11, 2019 at 11:11
  • It returns initial HTML only, If your component is re-rendering, It won't work.
    – Ashish
    Commented Jul 11, 2019 at 11:16
  • My component is not re-rendering but if still, what should I use now? Commented Jul 11, 2019 at 11:30
  • I think I am getting only the parent component but not its child component. Commented Jul 11, 2019 at 11:49
  • Cant say without checking codes for your component.
    – Ashish
    Commented Jul 11, 2019 at 13:36
2

There are two ways to do that. One is the renderToString() method, as the other answer mentions.

The other one is renderToStaticMarkup(): https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup

From docs:

Similar to renderToString, except this doesn’t create extra DOM attributes that React uses internally, such as data-reactroot. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.

If you plan to use React on the client to make the markup interactive, do not use this method. Instead, use renderToString on the server and ReactDOM.hydrate() on the client.

For sending email you don't need extra DOM attributes or hydration since the email doesn't include any JS code, renderToStaticMarkup() will do the job.

0

To get HTML from a react component, you can use theReactDOMServer.renderToString method (doc) used mainly for SSR purpose. However I guess you can achieve what you want with it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.