Skip to content

Instantly share code, notes, and snippets.

@kindacoder
Forked from scf4/app.js
Created January 10, 2022 18:44
Show Gist options
  • Save kindacoder/0dc07dbf8323fd891d64436539daedd4 to your computer and use it in GitHub Desktop.
Save kindacoder/0dc07dbf8323fd891d64436539daedd4 to your computer and use it in GitHub Desktop.
react native selectively highlight input text (mentions)
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