How to highlight a part of a text in TextInput react native

In my <TextInput> in react native I have to do a background color for each word which begin by '@'. I can detect the '@' but I never saw a documentation to highlight a part of a text. Not all the text, just a part.

I don't want to see my text in another <View> or <Text> as in this example : https://gist.github.com/scf4/012e9f615f6b43a1712a083b162afd94

I don't know if we have really a solution but thank you so much if you have it.

Upvotes: 2

Views: 3066

Answers (1)

raphaelmerx
raphaelmerx

Reputation: 724

This can be done by nexting Text elements inside of your TextInput:

<TextInput onChangeText={this.handleCheckTextChange}>
  <Text>{this.state.formattedText}</Text>
</TextInput>

The handle function will parse the text and create styled Text elements for all the mentions, so that formattedText will be an array of Text elements:

  handleCheckTextChange = (inputText) => {
    const words = inputText.split(' ');
    const formattedText = [];
    words.forEach((word, index) => {
      const isLastWord = index === words.length - 1;
      if (!word.startsWith('@')) {
        return isLastWord ? formattedText.push(word) : formattedText.push(word, ' ');
      }
      const mention = (
        <Text key={word + index} style={{color: 'red'}}>
          {word}
        </Text>
      );
      isLastWord ? formattedText.push(mention) : formattedText.push(mention, ' ');
    });
    this.setState({formattedText: formattedText});
  }

Demo: https://snack.expo.io/@raphaelmerx/text-per-word-style

Upvotes: 3

Related Questions