Reputation: 525
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
Upvotes: 0
Views: 162
Reputation: 2528
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
highlight = (string) => {
var boldString = "ABC"
var re = new RegExp(boldString, 'g')
var result = string.replace(re,"")
return{
boldText:boldString,
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>
Upvotes: 1
Reputation: 137
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>)
}
Upvotes: 3