Photo by Ferenc Almasi on Unsplash
Display a React component and its source code
How to use react-element-to-jsx-string
If you ever worked in a React component library you probably spent some time writing component documentation. Adding examples for each component and showcasing their source code is a worthwhile effort if you want to enable your users to quickly understand the components' different variations and use cases.
In this tutorial, we'll explore a powerful tool, react-element-to-jsx-string
, that simplifies the process of displaying React component source code alongside its rendered output.
PermalinkCreating our Button
component
First, let's create a very simple React component.
const Button = ({ children, ...rest }) => (
<button {...rest}>{children}</button>
);
export default Button;
PermalinkImporting the component into our app
Now we can simply display it in our app with a few lines of code.
import Button from "./Button";
const ButtonExample = () => <Button>I'm a button</Button>;
export default function App() {
return (
<>
<ButtonExample />
</>
);
}
PermalinkUsing reactElementToJSXString
Below our ButtonExample
is where we want to display its source code, in this case, <Button>I'm a button</Button>
but we first need to convert this React element into a string. That's when react-element-to-jsx-string
comes into play!
PermalinkInstall react-element-to-jsx-string
using npm
npm i react-element-to-jsx-string
PermalinkImport reactElementToJSXString
into our app
import Button from "./Button";
import reactElementToJSXString from "react-element-to-jsx-string";
const ButtonExample = () => <Button>I'm a button</Button>;
export default function App() {
return (
<>
<ButtonExample />
</>
);
}
PermalinkRender JSX code as a string
So now we're ready to display our ButtonExample
source code. Let's use a pre
tag to render our string and pass ButtonExample()
to reactElementToJSXString
.
import Button from "./Button";
import reactElementToJSXString from "react-element-to-jsx-string";
const ButtonExample = () => <Button>I'm a button</Button>;
export default function App() {
return (
<>
<ButtonExample />
<pre>{reactElementToJSXString(ButtonExample())}</pre>
</>
);
}
Easy right? The result should look something like this.
I hope you found this useful and make sure to check out the full example.