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?
Use the react-element-to-jsx-string
npm package and true
Npm package and use like this:
import React from "react";
import Button from "./Button.js";
import reactElementToJSXString from "react-element-to-jsx-string";
export default function App() {
var jsx = (
<div className="App">
{/*Hi*/}
{console.log("what")}
<h1 a={7}>test</h1>
<h2>h2</h2>
<Button />
</div>
);
return <pre>{ reactElementToJSXString(jsx, { showFunctions: true }) }</pre>;
}
which displays to the user:
<div className="App">
<h1 a={7}>
test
</h1>
<h2>
h2
</h2>
<Connect(Button) />
</div>
Actually you can just do App.toString()
and i think it will work