5

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?

2
  • That doesn't seem to be a valid JS. Commented Nov 30, 2015 at 15:48
  • If you're talking about the JSX component in the conditionals in the first code snippet, then that's because it hasn't been compiled into JS, which is how React works Commented Nov 30, 2015 at 15:53

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

I like the routeComponents[] idea, I didn't see how this[route.id] works... can you explain a bit more?
After thought, this[route.id] is not something you could do, so I have removed it from my answer.
Right ok, I was hoping for a safe way to transform a string but ill mark this as correct as it's probably the best way

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.