Pressable Component in React-native
In this blog, we are going to learn about the new component in react-native “Pressable“. We can say that it is an updated version of TouchableOpacity. It is a component wrapper similarly to TouchableOpacity means you have to define a child component in it. Pressable can detect various stages of pressing events.
“Pressable” provides us more functions to detect click-event like onPressIn, onPressOut, onPress, and onLongPress. I have used all the mentioned functions in the below snippet.
Let’s do some code:
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import React from 'react'; import { Pressable, StatusBar, StyleSheet, Text, ToastAndroid, View } from 'react-native'; import { Colors } from 'react-native/Libraries/NewAppScreen'; const App: () => React$Node = () => { function onPressFunction() { ToastAndroid.show("onPressFunction()",ToastAndroid.SHORT) } function onLongPress() { ToastAndroid.show("onLongPress()",ToastAndroid.SHORT) } function pressIn() { ToastAndroid.show("pressIn()",ToastAndroid.SHORT) } function pressOut() { ToastAndroid.show("pressOut()",ToastAndroid.SHORT) } return ( <> <StatusBar barStyle="dark-content" /> <View contentInsetAdjustmentBehavior="automatic" style={styles.container}> <Pressable onPress={onPressFunction} style={({ pressed }) => [ { backgroundColor: pressed ? Colors.light : Colors.dark }, styles.pressableStyle]} onLongPress={onLongPress} onPressIn={pressIn} onPressOut={pressOut} > {({ pressed }) => ( <Text style={ pressed ? styles.pressedTextStyle : styles.unPressedTextStyle}> {pressed ? 'Pressed!' : 'Press Me'} </Text> )} </Pressable> </View> </> ); }; const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems:'center', height:'100%', width:'100%' }, unPressedTextStyle: { padding:10, color: Colors.white, }, pressedTextStyle: { padding:10, color: Colors.black, }, pressableStyle: { borderRadius:5, shadowColor: '#000', shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.5, shadowRadius: 2, elevation: 5, } }); export default App; |
In conclusion, we will achieve this:
I hope it will help you to integrate the pressable component.
Reference link:- https://reactnative.dev/docs/pressable,