Buttons are used in all the programming language to get click events from users. But in react native we can also use its onStartShouldSetResponder Prop to enable click onPress event on View component. Because sometimes we have to make the View component responsive or Fire an event when user clicks on View. So here comes the onStartShouldSetResponder prop. It works same as button onPress event and can handle function calling. So in this tutorial we would learn about How to Set onPress on View using onStartShouldSetResponder React Native Android iOS Example.
Contents in this project Set onPress on View using onStartShouldSetResponder React Native Android iOS Example :-
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 Functional component named as App.
1 2 3 4 5 |
export default function App() { } |
3. Creating a function named as showAlert(). In this function we would print a Alert dialog box on the screen.
1 2 3 |
const showAlert = () => { Alert.alert('View Clicked ...'); }; |
4. Creating return block. Now here first we would make a Root View component -> 1 Child View component and set onStartShouldSetResponder on it to call the above function. So when user clicks on the View component it will call the function and print a Alert message on screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
return ( <View style={styleSheet.MainContainer}> <View style={styleSheet.view} onStartShouldSetResponder={showAlert} > <Text style={{ fontSize: 28, color: 'white', textAlign: 'center' }}> Set onPress onClick on View Component in React Native </Text> </View> </View> ); |
5. Creating Style.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const styleSheet = StyleSheet.create({ MainContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' }, view: { width: 350, height: 120, backgroundColor: 'coral', alignItems: 'center', justifyContent: 'center', } }); |
6. Complete Source Code for our React Native Project’s Main 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 40 41 42 43 |
import React from 'react'; import { View, StyleSheet, Text, Alert } from 'react-native'; export default function App() { const showAlert = () => { Alert.alert('View Clicked ...'); }; return ( <View style={styleSheet.MainContainer}> <View style={styleSheet.view} onStartShouldSetResponder={showAlert} > <Text style={{ fontSize: 28, color: 'white', textAlign: 'center' }}> Set onPress onClick on View Component in React Native </Text> </View> </View> ); } const styleSheet = StyleSheet.create({ MainContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' }, view: { width: 350, height: 120, backgroundColor: 'coral', alignItems: 'center', justifyContent: 'center', } }); |
Screenshots:-
