How to evaluate a string as a React component?

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!