-
-
Save vinhtran6921/335e508ec2f6f44e9a0084c15513cfe6 to your computer and use it in GitHub Desktop.
react native selectively highlight input text (mentions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { View, Text, TextInput, StyleSheet } from 'react-native'; | |
const styles = StyleSheet.create({ | |
wrapper: { | |
width: '90%', | |
height: 24, | |
position: 'relative', | |
alignSelf: 'center', | |
}, | |
inputWrapper: { | |
position: 'absolute', | |
top: 0, | |
height: 24, | |
width: '100%', | |
borderWidth: 1, | |
borderColor: 'gray', | |
}, | |
input: { | |
height: 24, | |
fontSize: 18, | |
width: '100%', | |
}, | |
text: { | |
height: 24, | |
fontSize: 18, | |
position: 'absolute', | |
top: 0, | |
color: 'transparent', | |
}, | |
mention: { | |
backgroundColor: 'rgba(0, 150, 255, .5)', | |
} | |
}); | |
export default class App extends React.Component { | |
state = { | |
inputText: '', | |
formattedText: '', | |
} | |
handleChangeText = (inputText) => { | |
const words = inputText.split(' '); | |
const formattedText = []; | |
words.forEach(word => { | |
if (!word.startsWith('@')) return formattedText.push(word, ' '); | |
const mention = ( | |
<Text key={word} style={styles.mention}> | |
{word} | |
</Text> | |
); | |
formattedText.push(mention, ' '); | |
}); | |
this.setState({ inputText, formattedText }); | |
} | |
render() { | |
return ( | |
<View style={{ marginTop: 48 }}> | |
<View style={styles.wrapper}> | |
<Text style={styles.text}> | |
{this.state.formattedText} | |
</Text> | |
<View style={styles.inputWrapper}> | |
<TextInput | |
style={styles.input} | |
value={this.state.inputText} | |
onChangeText={this.handleChangeText} | |
/> | |
</View> | |
</View> | |
</View> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment