0

I can covert JSX to a rendered output like so:

import { renderToString } from 'react-dom/server'

renderToString(<YourAwesomeComponent props1="value1" props2={{ value: '2' }} />)

which yields:

<div> ... </div>

In other words, the text is what would end up in the browser.

The text I want to get is the original code:

"<YourAwesomeComponent props1=\"value1\" props2={{ value: '2' }} />"

How can this be done?

Thanks,

Eduardo

Edy Bourne
  • 5,679
  • 13
  • 53
  • 101
  • 1
    You can't since JSX is compiled away before execution. You could write a custom function to reconstruct it from the props and types but you won't get it *exactly* as it was in your code. Or you need to have a step that happens before JSX is transpiled into regular javascript. Maybe look into webpack / babel plugins? You could read your file as a string with node, pass the string to babel's AST parser, and extract a JSX string from the javascript syntax tree. – Sheraff Dec 21 '22 at 22:08

0 Answers0