Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rich ReactNative TextInput

Tags:

react-native

Any way to create a "rich" TextInput in React Native? Maybe not a full blown wysiwyg, but maybe just change the text color of various pieces of text; like the @mention feature on Twitter or Facebook.

like image 556
nicholas Avatar asked Jun 17 '16 20:06

nicholas


People also ask

What is TextInput in React Native?

TextInput is a Core Component that allows the user to enter text. It has an onChangeText prop that takes a function to be called every time the text changed, and an onSubmitEditing prop that takes a function to be called when the text is submitted.

How do I clear TextInput in React Native?

To clear React Native TextInput, we can set the value with a state and clear the state. to set the value prop to val . And we set onChangeText to setVal to set val to the inputted value. Next, we add a Button with the onPress prop set to a function that set val to an empty string with setVal .


2 Answers

This question was asked a while ago but I think my answer can help other people looking for how to color the @mention part of a string. I am not sure if the way I did it is clean or the "react" way but here is how I did it: I take the inputed string and split it with an empty space as the separator. I then loop through the array and if the current item matches the pattern of @mention/@user, it is replaced with the Text tag with the styles applied; else return the item. At the end, I render inputText array (contains strings and jsx elements)inside the TextInput element. Hope this helps!

render() {
let inputText = this.state.content;
if (inputText){
  inputText = inputText.split(/(\s)/g).map((item, i) => {
    if (/@[a-zA-Z0-9]+/g.test(item)){
      return <Text key={i} style={{color: 'green'}}>{item}</Text>;
    } 
    return item;
  })
return <TextInput>{inputText}</TextInput>

Result

like image 29
Abubakar Ibrahim Avatar answered Oct 10 '22 01:10

Abubakar Ibrahim


Solution is that you can use <Text> elements as children in a <TextInput> like this:

<TextInput>
    whoa no way <Text style={{color:'red'}}>rawr</Text>
</TextInput>
like image 141
Noitidart Avatar answered Oct 10 '22 03:10

Noitidart