Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to get children as string?

Tags:

reactjs

I am writing documentation for a a couple of components we are building, so the doc (which is also a react component looks like this:

const myDoc = () => (
  <div>
    <MyComponent title="MyTitle" />
    <code className="language-jsx">
       {`<MyComponent title="MyTitle" />`}
    </code>
  </div>
)

See the duplication on MyComponent? So I created the "Code" Component to handle that:

const Code = ({ children }) => (
  <div>
    {children}
    <code>
       {children}
    </code>
  </div>
)

Then MyDoc now is:

const myDoc = () => (
  <Code>
    <MyComponent title="MyTitle" />
  </Code>
)

But since children inside Code is a object, it will not render as string.

Is there a way to achieve this? Or maybe a better solution?

like image 660
Gileno Avatar asked Jun 27 '26 23:06

Gileno


1 Answers

I was also writing documentation and I also didn't want to change the markdown files every time I change demo. I wanted something like element.innerHTML equivalent.

I stumbled upon this answer and on further searching I found this package called jsxToString in github.

Just mentioning in case someone else is also trying to do documentation and stumbles in this post.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!