Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native create element with string

I see a lot people creating a route mapping in React native similar to the below:

if (route.id === 'Blah') {
    return  (<Blah prop1={this.method} prop2={this.other method} />);
} else if (route.id === 'OtherView') {
    return (<OtherView prop1={this.method} />);
}

this can quickly become many lines of code, I'd like to do something like this:

return (React.createElement(route.id, {propsToPass}));

This doesn't work in React Native as apparently 'strings are not allowed as the first parameter in React Native since those are meant to be used for html tags in regular React.'

So how can this be done? I got it working if I supply a ReactClass as the first param, or with eval(route.id) (but I know that can be dangerous).

How can I create a React Native element with a string?

like image 299
Ben Taliadoros Avatar asked Oct 18 '22 21:10

Ben Taliadoros


1 Answers

You could setup an allowed components namespace:

var routeComponents = {
  "Blah": Blah,
  "OtherView": OtherView
}

if(routeComponents[route.id]) {
  return React.createElement(routeComponents[route.id], {propsToPass});
} else {
  // Error
}
like image 155
Marc Greenstock Avatar answered Oct 22 '22 02:10

Marc Greenstock