How to apply style for part the text in React Native’s TextInput?

Viewed 887

I’d like to color part of the text when the user enters a text using TextInput. For example, when a word starts with @, then I’d like to color the whole word with red. Is it possible?

2 Answers

You can actually do it by nesting Text elements inside of a 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:

  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

You can refer to my Expo snack. Split the words, check for the '@' and render each word separately and change the style when it passes the condition.

Related