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?
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