Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native render Components from String variable

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.

like image 807
Awa Melvine Avatar asked Aug 23 '26 18:08

Awa Melvine


1 Answers

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 )

like image 132
Vasiliy Vanchuk Avatar answered Aug 26 '26 08:08

Vasiliy Vanchuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!