react-live icon indicating copy to clipboard operation
react-live copied to clipboard

Question: How to turn React Component into String

Open Kikobeats opened this issue 2 years ago • 0 comments

Hello, I love this project, thanks for it 🙂

I'm trying to do a better integration of it in cards.microlink.io:

The user write react code in the right, it's rendered on the left, and that is used in combination of api.microlink.io for generating social images, like this:

https://api.microlink.io/?adblock=false&waitForTimeout=1500&meta=false&screenshot&element=%23screenshot&embed=screenshot.url&url=https%3A%2F%2Fcards.microlink.io%2F%3Fpreset%3Dapple-accessibility

The code can be previously declared as a "preset": https://github.com/microlinkhq/cards/blob/master/packages/app/src/components/presets/kikobeats.js#L12

That's actually the code that is passed to react-live, but there is a detail there: the code is actually React code, and it should be passed as a string.

Did you see the <Inline /> component on the top? that's actually a babel macro to transform the React code into a string:

https://github.com/microlinkhq/cards/blob/master/packages/app/src/components/inline.macro.js#L23

(It's using prettier under the hood for that, since prettier output is a string)

Although that is working fine, it makes the setup a bit tedious from a user perspective. What I want to do in order to make the setup simpler for the user is to remove the <Inline />.

The problem is, in order to make the "inline" transform, it should be declared at that level, so I tried to find another way to get a string as output, so the user doesn't need to know that implementation detail.

I found in this repo you are doing something similar as part of your test suite: https://github.com/FormidableLabs/react-live/blob/ac553e6427ec5fc480b21108751e7ba864b11a10/src/utils/test/renderer.js

However, that setup is producing HTML markup as output.

my TLDR question here is: is it an easy way to transform a React component:

const MyComponent = () => <small>Hello World</small>

into a string representation that is the input expected by react-live?

`const MyComponent = () => <small>Hello World</small>`

Kikobeats avatar Feb 02 '23 13:02 Kikobeats