0

I'm trying to write a code-editor using react-live.

The following works, where I hardcode the sample code into a string:

const code="<div>hello</div";
...
<LiveProvider code={code}>
  <LiveEditor />
  <LiveError />
  <LivePreview />
</LiveProvider>

But, for more advanced usages (when there is more than a trivial amount of example code), it is not efficient to write code inside a string. So, my underlying question is how can we effectively write example code which populates a code-editor?

Ideally, we could write the sample code in a separate module, as actual code, and then somehow read it in when setting up the code-editor component. However, this doesn't work:

import sampleCode from "./sampleCode.jsx";
const code = sampleCode.toString(); // '[object Object]'

Additionally, defining the sample code right there within the file doesn't work:

const code = <div>hi</div>;
code.toString(); // '[object Object]'

How can I convert actual code snippets into a string representation?

1 Answer 1

1

What if you create a sample string and export it from a js file then import it and pass it in the code prop. I don't see an issue here. You can also lazily import samples.

Here's a simple use case:

// codeSamples.js

export const sample = `
const Sample = (props) => {
    return (
      <h1>Sample!</h1>
    );
}
`.trim();

// Component.js

import { sample } from "./codeSample";

...
<LiveProvider code={sample}>
  <LiveEditor />
  <LiveError />
  <LivePreview />
</LiveProvider>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.