1

I have a Component:

function MyComp(props) {
  return (
    <div class="myJSX">
      Some Content.
      { props.children }
    </div>
  )
}

I want to get the outerHTML before I render it.

More emphasis on before

Question is about before rendering, answers like this won't help me.

By render, I mean calling ReactDOM.render

Note: This is in Node.js not purely in-browser. Any node related answer is also very helpful.

No Idea is too bad.

So the outer HTML of:

<MyComp>hello</MyComp>

should look like:

<div class="myJSX">
  Some Content.
  hello
</div>
Community
  • 1
  • 1
Angshu31
  • 1,172
  • 1
  • 8
  • 19

1 Answers1

2

"I want to get the outerHTML before I render it." But rendering is basically creating a structure that will be converted to html.

With a few assumptions:

  • By "before" you mean before rendering on a client
  • You want this in your backend ("This is in Node.js").

You could use ReactDOMServer.renderToString method

Something like this

const {renderToString} = require('react-dom/server');

const html = renderToString(<MyComp>Hello</MyComp>)
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Best answer yet, i'm just going to check this, and accept it. – Angshu31 Jun 09 '20 at 11:12
  • That's not [outerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) like the OP asked, but it really what he might mean in his problem – Dennis Vash Jun 09 '20 at 11:17
  • @DennisVash It is hard to say what outer html for react component even means. But the result would be exactly what OP has posted as a desired output. – Yury Tarabanko Jun 09 '20 at 12:21
  • @YuryTarabanko It is not true, `renderToString` and `outerHTML` don't give the same output, you can check it – Dennis Vash Jun 09 '20 at 12:22
  • Reread the question plz. OP has posted desired output and renderToString would give exactly that. There is no such thing as outerHTML (or innerHTML, or adjacentHTML) for react components. JSX is not html though `Hello` looks like one. – Yury Tarabanko Jun 09 '20 at 12:26
  • Of course there isn't, you get the `outerHTML` from the reference, and the question is "How to get JSX Element's outerHTML ...?", you literally can see my deleted answer – Dennis Vash Jun 09 '20 at 12:29