Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 595
ofer2980 Avatar asked Oct 12 '25 01:10

ofer2980


1 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

like image 179
raphaelmerx Avatar answered Oct 15 '25 17:10

raphaelmerx