chirag arora
chirag arora

Reputation: 131

How to get html code from reactjs component

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.

Upvotes: 12

Views: 20404

Answers (3)

user3132457
user3132457

Reputation: 1019

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.

Upvotes: 2

Ashish
Ashish

Reputation: 4330

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.

Upvotes: 19

Ga&#235;l S
Ga&#235;l S

Reputation: 1569

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.

Upvotes: 0

Related Questions