0

In my electron application, I want to offer some kind of extensibility for the UI. The users should be able to create a react component inside of a text editor inside of my application. Their code gets saved to a file. They also can define where the component should be placed inside my UI.

The problem is: I can't seem to figure out how to parse and inject the user-defined JSX in my existing react app.

I thought I try with babel transformSync, but I can't get it working. This is what I have so far:

const DynamicComponent = (props) => {
  const reactCode = `
    return (
      <div>
        <h1 >Hello, World!</h1>
      </div>
    )
  `;

  const transpiledCode = transform(reactCode, {
    presets: ["@babel/preset-react"]
  }).code;

  console.log("transpiled", transpiledCode);
  globalThis["React"] = React;
  const Dynamic = new Function(`return ${transpiledCode}`)();
  return <Dynamic />;
};

https://codesandbox.io/s/mobx-state-tree-todolist-3umd4?file=/components/TodoList.js

I'd like to have the "<h1>Hello, World!</h1>" rendered below my todo list.

1 Answer 1

4

This took sometime. Here are somethings to be aware of:

  1. The @babel/core gives an invalid version error, so I used the @babel/runtime version since it's designed for use in the browser.
  2. I found out that removing comments while using the @babel/core helped with automatic semicolon insertion problem with js.
  3. You need to return your new DynamicComponent directly. Do not convert it to ReactElement by returning <Dynamic />.

See codesandbox here

const DynamicComponent = (props) => {
  const reactCode = `
       <div>
          <h1>Hello, World!</h1>
        </div>
  `;

  const transpiledCode = transform(reactCode, {
    presets: [
      "react",
      {
        comments: false
      }
    ]
  }).code;

  globalThis["React"] = React;

  return new Function(`return ${transpiledCode}`)();
};

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

1 Comment

Amazing- I would not have figured it out I think!

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.