How to render component as text in react-native

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to render component as text in react-native



Can somebody help me to render Text from a component from a function? This is my case. I have a function to hightlight a custom character in a string. The function is like this.


highlight = (string) =>
var re = new RegExp('ABC', 'g')
var result = string.replace(re, <Text style= fontWeight : 'bold' >ABC</Text>)
return(
<Text>result</Text>
)



Then, in render function of my class, I call this function like this:


<Text style=marginBottom: 10>
this.highlight('ABC DEF GHI')
</Text>



The goal is, I want to give bold ABC from ABC DEF GHI. But when I run this, the result is like this : [object Object] DEF GHI.. Can somebody help me so the result is ABC DEF GHI


ABC


ABC DEF GHI




2 Answers
2



The words will always be separated by a blank space? If so, I would do a solution like this:



'ABC DEF GHI'.split(" ").map(
s => s.match('ABC', 'g') ?
<Text style= fontWeight : 'bold' >s</Text> :
<Text>s</Text>)



The [object Object] is actually the error statement which is caused by this line in your code


var result = string.replace(re, <Text style= fontWeight : 'bold' >ABC</Text>)



Now your result variable become and object as string.replace(re, <Text style= fontWeight : 'bold' >ABC</Text>) return error.

this is because second argument of replace must be string else it will give unexpected token... error.

to solve this You can do this


<Text style= fontWeight : 'bold' >ABC</Text>


highlight = (string) =>
var re = new RegExp('ABC', 'g')
var result = string.replace(re,"")
return
boldText:"ABC",
regularText:result





and in your render function


<Text style=marginBottom: 10>
<Text style= fontWeight : 'bold' >this.highlight("ABC DEF GHI").boldText</Text>
this.highlight('ABC DEF GHI').regularText
</Text>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered