Hello friends, As button the Text component does also support onPress event in react native. The onPress event is called when user touch or press the Text component. To Set onPress onClick on Text in React Native we have to use onPress={} prop in react native. The onPress event is supported by both Android and iOS platforms.
Contents in this project Example of Set onPress onClick on Text in React Native :-
1. Open your project’s main App.js file and import View, StyleSheet, Text and Alert component.
1 2 3 |
import React from "react"; import { View, StyleSheet, Text, Alert } from 'react-native'; |
2. Creating our main Export default App component .
1 2 3 4 5 |
export default function App() { } |
3. Creating a function named as showMessage() with Fat Arrow ()=> syntax. In the function we are simply print a Alert message on screen.
1 2 3 4 5 |
const showMessage = () => { Alert.alert('onPress Called...'); } |
4. Now we would make the return() block and make 1 Text component with onPress={ } event and call above function in it.
1 2 3 4 5 6 7 8 9 10 11 |
return ( <View style={styleSheet.MainContainer}> <Text style={{ color: 'red', fontSize: 30, textAlign: 'center' }} onPress={showMessage}> Example of onPress Click Event on Text in React Native </Text> </View> ); |
5. Creating Style.
1 2 3 4 5 6 7 8 9 10 |
const styleSheet = StyleSheet.create({ MainContainer: { flex: 1, padding: 10, justifyContent: 'center', alignItems: '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 |
import React from "react"; import { View, StyleSheet, Text, Alert } from 'react-native'; export default function App() { const showMessage = () => { Alert.alert('onPress Called...'); } return ( <View style={styleSheet.MainContainer}> <Text style={{ color: 'red', fontSize: 30, textAlign: 'center' }} onPress={showMessage}> Example of onPress Click Event on Text in React Native </Text> </View> ); } const styleSheet = StyleSheet.create({ MainContainer: { flex: 1, padding: 10, justifyContent: 'center', alignItems: 'center' } }); |
Screenshots :-
