3

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.

4
  • 1
    duplicate: stackoverflow.com/questions/42652785/… Commented Jul 31, 2018 at 8:31
  • @Awa Melvine, Same problem not, found any solution if you found any kindly please share it Commented May 2, 2020 at 11:21
  • @Awa Melvine any updates on this question please?? Commented Jan 25, 2022 at 15:15
  • @Muhammad if u got a solution please consider sharing it Commented Jan 25, 2022 at 15:16

3 Answers 3

2

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 )

Sign up to request clarification or add additional context in comments.

Comments

0

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!)

Comments

0
+50

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>

Comments

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.