I am writing a page to illustrate how to use a component I’ve developed and I’d like to build pairs of examples (rendered) with TSX source code that produces the example, ideally not having to repeat the code twice. I’d love to be able to grab the ref to the rendered component and get the TSX code from it to then inject it in a <pre>
element and apply the highlighting. However the best I can seem to do is get the ìnnerHTML
, which returns the component as rendered in the DOM, not the TSX code. Is there a way to achieve this? Or even better, a library that already does?
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
2
Answers
No, it’s not possible to get the JSX/TSX of a React component from the code itself. This is because JSX/TSX is a syntax extension for JavaScript and it’s not a part of the JavaScript runtime. When your code is transpiled, the JSX/TSX syntax is transformed into JavaScript code that creates React elements. The original JSX/TSX code is not preserved in the transpiled output.
Use the
react-element-to-jsx-string
npm package andtrue
Npm package and use like this:and it outputs: