skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Use the react-element-to-jsx-string npm package and true Npm package and use like this:

    import React from 'react';
    import reactElementToJSXString from 'react-element-to-jsx-string';
    import t from 'true'
    
    console.log(reactElementToJSXString(<div a="1" b="2">Hello, world!</div>), {showFunctions:t()});
    

    and it outputs:

    <div
      a="1"
      b="2"
    >
      Hello, world!
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search