Use string as JS file that declares a react component

Viewed 325

I'm using a plugin (react-simple-code-editor) thar allow me to edit a complete JS file from the imports untils the end of a component declaration.

react simple code editor

This editor returns a string with all the file declaration. In this example, it would be:

import React from "react"; import ReactDOM from "react-dom"; function App() { return ( <h1>Hello world</h1> ); } export default App;

Is there a way to use this string, as code. I Mean, render it, or read it like if it is a normal file ?

I've tried react-jsx-parser, but it only works with strings that are the component, not complete JS files.

1 Answers

Try using eval. eval() will run its input (type string), as if it were part of the program:

string = "import React from 'react'; import ReactDOM from 'react-dom'; function App() { return ( <h1>Hello world</h1> ); } export default App;";
eval(string);

You will notice that the MDN docs include a warning not to use eval for security reasons. This is because it executes the code with all the permissions the user has granted the webpage, so if there is a chance that someone evil could have modified the string, then they can run whatever code they want on the client's device. This is only an issue for certain use cases, though, and probably not yours. See "How evil is eval?". It is also slightly slow due to the fact that the code must be compiled, but for your example this won't really be noticeable.

Related