Skip to content

Instantly share code, notes, and snippets.

@scf4
Last active March 12, 2025 13:02
Show Gist options
  • Save scf4/012e9f615f6b43a1712a083b162afd94 to your computer and use it in GitHub Desktop.
Save scf4/012e9f615f6b43a1712a083b162afd94 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>
);
}
}
@Lu1815
Copy link

Lu1815 commented Apr 26, 2024

@scf4 Not really, I think most build their own stuff with react native. I saw this(https://github.com/harshq/react-native-mentions), but it's not so modular.

We can definitely make one!

Your snippet was very helpful for syntax highlighting.

Here's the finished result 68747470733a2f2f6d656469612e67697068792e636f6d2f6d656469612f4a6d4f48357054724f3541364f556c4536622f67697068792e676966

@comphonia hey man, do you have some source code for what you showed in the gif?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment