Ben Taliadoros
Ben Taliadoros

Reputation: 9451

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?

Upvotes: 5

Views: 3043

Answers (1)

Marc Greenstock
Marc Greenstock

Reputation: 11688

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
}

Upvotes: 3

Related Questions