Alen.Toma
Alen.Toma

Reputation: 4870

Create class/component from string

Say i have a file like below on the server eg Github. I want to download the file as string with fetch and then be able to convert it to an object that i could use.

OBS: all import and the interface exist on locally so there wont be any thing missing.

import parser from '../interface/parsers';
import '../interface/extension';

export default class test implements parser {
  public name: string;
  constructor() {
  
    }
  
  }

Upvotes: 0

Views: 48

Answers (1)

jnpdx
jnpdx

Reputation: 52535

Here's an example that at least works in a Snack (ignored the fetch part and just used a local string):

export default function App() {
  
  const [evaledComponent, setEvaledComponent] = useState(null)

  useEffect(() => {
    this.React = React;
    this.Text = Text;  
    setEvaledComponent(eval('this.React.createElement(this.Text, {}, "test component")'));
  },[])

  return <Text>{evaledComponent}</Text>  

}

Note: I took a trick from from Why eval() is not working in React Native? assigning React to this.React in order to get it usable -- it's not a pretty hack and I'd recommend a more stable solution if you went ahead with this plan.

But:

This is an extremely uphill battle to take on and using eval is a terrible security risk since it executes arbitrary code. If there's another route you can take (like rendering things based on a JSON description), I would take that route instead.

Update:

Example of returning a custom object (non-React)

eval("var MyParser = { getString: () => {return 'hi there'} }");

return <Text>{MyParser.getString()}</Text>  

Upvotes: 1

Related Questions