Search code examples
javascriptreactjstypescriptreflectiontsx

Is there a way to get the JSX/TSX of a React component from the code itself?


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?


Solution

  • 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>