Text Highlighter is used by many students to high light main points in notes or text book. It is also used in many Android iOS Education based applications to highlight some important text which is marked by professors. In react native we can easily achieve this type of functionality using Text component. So in this tutorial we would learn about React Native Highlight Some Text Within Text String Yellow Color.
Contents in this project React Native Highlight Some Text Within Text String Yellow Color:
1. Open your project’s main App.js file and import View, StyleSheet and Text component.
1
2
3
|
import React from ‘react’ ;
import { View, StyleSheet, Text } from ‘react-native’;
|
2. Create our main export default function App(). This is our main Root Parent functional component.
1
2
3
4
|
export default function App() {
}
|
3. Creating a Constant type method named as highlightText with String Argument. Inside this method we would apply the Highlighter effect on given text string. We would call this method directly inside the Text component and pass the Text which we want to highlight.
1
2
3
4
5
6
|
const highlightText = string =>
string.split(‘ ‘).map((word, i) => (
<Text key={i}>
<Text style={styles.highlightText}>{word} </Text>
</Text>
));
|
4. Creating return block. Inside the return block we would first make a Root View component and then we would make a Text component. Inside the Text component we would call the method highlightText() and pass the Text string inside it.
1
2
3
4
5
6
7
8
9
10
|
return (
<View style={styles.MainContainer}>
<Text style={{textAlign: ‘center’, fontSize:26}}>
Hello Friends, Welcome To our Website {highlightText(‘ReactNativeCode.com’)}
</Text>
</View>
);
|
5. Creating Style.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’
},
highlightText:{
backgroundColor: ‘yellow’,
fontSize: 26,
textAlign: ‘center’
},
});
|
6. Complete Source Code for App.js file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import React from ‘react’ ;
import { View, StyleSheet, Text } from ‘react-native’;
export default function App() {
const highlightText = string =>
string.split(‘ ‘).map((word, i) => (
<Text key={i}>
<Text style={styles.highlightText}>{word} </Text>
</Text>
));
return (
<View style={styles.MainContainer}>
<Text style={{textAlign: ‘center’, fontSize:26}}>
Hello Friends, Welcome To our Website {highlightText(‘ReactNativeCode.com’)}
</Text>
</View>
);
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’
},
highlightText:{
backgroundColor: ‘yellow’,
fontSize: 26,
textAlign: ‘center’
},
});
|
Screenshot: