Search code examples
react-nativetextinput

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


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?


Solution

  • 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