2

I'm trying to make a website that lets users input some react code, then it renders it on the other side of the page, so they can see what it looks like.

My problem is, I have the user's source code as a string (which may return a function or class component), but I don't know how to convert that to an actual react component that can be rendered.

First I tried using the new Function() constructor, which lets you create a function from a string, which looks like this:

import {render} from "react-dom"

const userInputtedCode = `
return function App() {
    return <div>Hello world</div>
}
`

const func = new Function("React", userInputtedCode);
const App = func(React)
render(<App/>, document.getElementById('WorkFlow'));

But this doesn't work, as I get the error SyntaxError: expected expression, got '<'

I have also tried libraries such as react-jsx-parser, but this doesn't fit what I need, as I want to make an entire react component which may contain state, props, nested components, etc, not just parse some JSX.

Any ideas of how I can convert strings of source code that return a function/class into actual react components? Thanks!

2
  • 3
    JSX is transpiled with babel before the code is even send to the browser Commented Nov 29, 2022 at 20:39
  • 1
    Is that for learning purposes? Any advantage over codesandbox / stackblitz? Commented Nov 29, 2022 at 20:42

1 Answer 1

4

You can try this approach:

import React, { Component } from "react";
import { render } from "react-dom";
import * as babel from "babel-standalone";

const userInputtedCode = `
function App() {
    return <div>Hello world</div>
}
`;
const babelCode = babel.transform(userInputtedCode, {
  presets: ["react", "es2017"]
}).code;

const code = babelCode.replace('"use strict";', "").trim();
const func = new Function("React", `return ${code}`);
const App = func(React);
render(<App />, document.getElementById("root"));

PS: Make sure to run npm i babel-standalone before running the app.

Sign up to request clarification or add additional context in comments.

2 Comments

This works for the example, and works with other examples such as adding const data = 0 inside the App function and then return <div>Data is {data}</div>, but if instead of const data = 0 you put const [data, setData] = React.useState(0) it does not work, it gives the error SyntaxError: expected expression, got keyword 'var' - why is this, and is there any way to fix it?
const babelCode = babel.transform(userInputtedCode, { presets: ["react", "es2017"] }).code; Change the ES version to es2017 and it should work! @Yankue

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.