J.Todd
J.Todd

Reputation: 827

Can I apply styles to a subset of the text in a user input with React Native?

Let's say in a TextInput element, I want to make a word green if it's formatted as @someonesusername the moment they finish writing the word (as opposed to after the text is submitted, in which case it's trivial to send the text to a normal Text component with subset styling. I thought of underlaying a Text component with absolute positioning and making the actual TextInput component invisible, but that seems it might be a headache to keep in sync, and cause usability challenges in the sense that the editing cursor wouldn't be there unless you wired together a custom cursor element to render and that'd be quite the headache for such a small thing I want to do.

Upvotes: 0

Views: 235

Answers (1)

Subhendu Kundu
Subhendu Kundu

Reputation: 3856

So this the hack I came up with (Amazing question). React native TextInput can take children as input. So why not split the value and add Text as children in the TextInput and add style the way you want to. May be wondering how do get the text back? Well these children become string when comes to onChangeText callback and get a string back in your state. For example:

// split the text like
const [firstPart, secondPart] = this.state.text.split("@");
const [higlighted , restText] = secondPart ? secondPart.split(' ') : [];

Then use them

<TextInput
  style={{height: 40, borderColor: 'gray', borderWidth: 1}}
  onChangeText={this.onChangeText}
>
  <Text style={styles.paragraph}>
    <Text>{firstPart}</Text>
    {higlighted && <Text style={{
      color: 'blue'
    }}>@{higlighted}</Text>}
    {restText !== undefined && <Text> {restText}</Text>}
  </Text>
</TextInput>

Umm, I accept this might be worse solution ever but this works :P

Full example: https://snack.expo.io/@subkundu/react-native-styles-to-a-subset-of-the-text

enter image description here

Upvotes: 1

Related Questions