Hello friends, In today’s tutorial we would learn about hitSlop prop in react native, How hitSlop works with View and TouchableOpacity button. The main work of hitSlop is to increase the touchable area of a View or button. So using this we can make a Touchable View completely clickable or a part of it clickable. So in this tutorial we would learn about Example of hitSlop Prop in View TouchableOpacity in React Native Android iOS.
Contents in this project Example of hitSlop Prop in View TouchableOpacity in React Native :-
1. Open your project’s main App.js file and import View, StyleSheet, Text and TouchableOpacity component.
1 2 3 |
import React from 'react'; import { View, StyleSheet, Text, TouchableOpacity } from 'react-native'; |
2. Creating our main export default App component.
1 2 3 4 5 |
export default function App() { } |
3. Creating return() block, Now here we would first make a Root View component -> make a Child View component and put the Touchable Opacity button inside it. Now we would apply the hitSlop prop on Touchable and set its area on all top, left, bottom and right side.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
export default function App() { return ( <View style={styleSheet.MainContainer}> <View style={styleSheet.buttonStyle}> <TouchableOpacity onPress={() => { console.log('Button Clicked') }} hitSlop={{ top: 50, bottom: 50, left: 50, right: 50 }} > <Text style={{ fontSize: 26, textAlign: 'center', color: 'white' }}> Button With hitSlop </Text> </TouchableOpacity> </View> </View> ); } |
4. Creating Style.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const styleSheet = StyleSheet.create({ MainContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' }, buttonStyle: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#00C853', width: 350, height: 100, borderRadius: 5 }, }); |
5. 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 |
import React from 'react'; import { View, StyleSheet, Text, TouchableOpacity } from 'react-native'; export default function App() { return ( <View style={styleSheet.MainContainer}> <View style={styleSheet.buttonStyle}> <TouchableOpacity onPress={() => { console.log('Button Clicked') }} hitSlop={{ top: 50, bottom: 50, left: 50, right: 50 }} > <Text style={{ fontSize: 26, textAlign: 'center', color: 'white' }}> Button With hitSlop </Text> </TouchableOpacity> </View> </View> ); } const styleSheet = StyleSheet.create({ MainContainer: { flex: 1, alignItems: 'center', justifyContent: 'center' }, buttonStyle: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#00C853', width: 350, height: 100, borderRadius: 5 }, }); |
Screenshot :-