Home > Blockchain >  Convert HTML (JSX) from React into a string [duplicate]
Convert HTML (JSX) from React into a string [duplicate]

Time:09-27

How would I take HTML stored in a variable and convert it into a string?

Take this:

var html = <div>html</div>;

And Make it into this:

var html = "<div>html</div>"

CodePudding user response:

You can get the element's outerHTML property:

var elem = document.querySelector('div');

var res = elem.outerHTML;

console.log(JSON.stringify(res))
<div>html</div>

CodePudding user response:

As per the flagged duplicate you can use ReactDOMServer.renderToString(element), or ReactDOMServer.renderToStaticMarkup(element) to render a react element as an HTML string (renderToStaticMarkup() doesn’t render the extra DOM attributes that React uses internally, such as data-reactroot).

Both methods can be used in both the server and browser environments.

function App() {

const html = (<div>html</div>);

return (
  <div>
    {ReactDOMServer.renderToStaticMarkup(html)}
  </div>
  )
}

ReactDOM.render(
  <App  />,
  document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom-server.browser.production.min.js"></script>

<div id="root"></div>

  • Related