How can I turn a string with style information into Text Components?

By : Squeaky

For example, I have a string:

"Wherefor art <strong>thou</strong> mr. <strong>fancypants</strong>"

I need to turn this into react-native Text components and back to a render() method. So the string would be transformed into:

<Text>Where for art <Text style={{ fontweight : 600}}>thou</Text> mr. <Text style={{fontweight: 600}}>fancypants</Text>;

So my render method looks like this:

render() {
  let text = "Wherefor art <strong>thou</strong> mr. <strong>fancypants</strong>";
  return (
    <View style={{marginBottom : 20}}>

And what I tried for turning text into components, which obviously doesn't work:

filterHtml = (text) => {
  if (text) {
    return text.replace(/<strong>([^<]*)<\/strong>/g, "<Text style={{fontweight : 600}}>$1</Text>")
  return text;

Not surprisingly what ends up happening is this literal string being rendered inside the <Text> element as shown in the render method:

"Where for art <Text style={{ fontweight : 600}}>thou</Text> mr. <Text style={{fontweight: 600}}>fancypants".

Any ideas?

By : Squeaky


Try this:

By : vijayst

A not-very-good solution: Use the HTML function in the Webview. So something like:

By : dv3

You asked how to split into multiple text components but it sounds like your end goal is to display html appropriately. If that is truly the case check out react-native-htmlview. If that is not your intent you can at least see how they tackled this problem.

By : Steven

This video can help you solving your question :)
By: admin