Reputation: 4087
Or maybe the question should have been, How to convert string to JSX?
In any case, I am trying to do a performance hack on my react native app that requires me to render React native components from a string variable.
For instance,
let item = "<View>
<Text>
This is an item
</Text>
</View>";
Now in my render function, I want to render it like so:
render() {
return (
<View>
{item}
</View>
);
}
As it is now if I try to run the application it gives an error because I am trying to render text inside a View
component. If I try to wrap the item inside text before rendering, It just renders the item as plain text on the screen, with all the <View>
and <Text>
tags as strings.
How can I then render this so that the tags from the string behave as normal React Native component instead of just appearing as strings?
I have searched all over but haven't found a solution.
I will appreciate any suggestions.
Upvotes: 3
Views: 7470
Reputation: 51
I think the only solution for this problem, is to declare your variable like so :
var str = <Detail_page1/>
and then wrap it with a view like this :
<View> {str} </View>
Upvotes: 0
Reputation: 7169
Try one of these two packages:
https://www.npmjs.com/package/acorn-jsx
https://www.npmjs.com/package/react-jsx-parser
Both allow to parse a string to jsx on the fly (Have no chance to test in RN, but for React in web works fine )
Upvotes: 2
Reputation: 2684
If you put object instead of string you can easily set it inside view. But if you want to use string, you have to write a converter and extract each element as string and check and convert to it's equivalent view.
If your views have props you have to convert them also(it will be a little bit harder!)
Upvotes: 0