Q:

How to properly highlight text in React Native?

I would like to highlight a multiline text in a React Native app by changing the text's background color. The problem is that the background color changes in the whole text area, not just under the words.
class Example extends Component {
  render() {
    const text = '...';

    return (
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>
          {text}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  textContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: 200,
  },
  textStyle: {
    backgroundColor: 'red',
  },
});

The code above results in something that looks like this: 
But I would like it to look like this: 
I can get that result by splitting the text and adding the background color to the individual words:
class Example extends Component {
  render() {
    const text = '...';

    const brokenText = text.split(' ').map(word => (
      <Text style={styles.textStyle}>{word} </Text>
    ));

    return (
      <View style={styles.textContainer}>
        {brokenText}
      </View>
    );
  }
}

But splitting the text into individual words doesn't seem like the best solution, and has a huge performance cost. Is there any cleaner way to do it?

A:

This is still not proper but I had it rendering as you expect by adding an invisible character (no-width space here) between each word, so the text breaks on it which has no background color. Here is the code :  
const NO_WIDTH_SPACE = '​'; // This is a special char you should copy and paste, not an empty string!

const Example = () => {
  const highlight = string =>
    string.split(' ').map((word, i) => (
      <Text key={i}>
        <Text style={styles.highlighted}>{word} </Text>
        {NO_WIDTH_SPACE}
      </Text>
    ));

  return (
    <Text>
      Some regular text {highlight('with some properly highlighted text')}
    </Text>
  );
}

const styles = StyleSheet.create({
  highlighted: {
    backgroundColor: 'yellow',
  },
});

Here is a Snack where you can see the result and play with it : https://snack.expo.io/@adesurirey/properly-highlight-text-with-react-native

It can surely be improved, I'll be happy to have feedback.

