Summary: In this tutorial, you will learn how to use the React Native Pressable component to detect various touch interactions, such as pressing, hovering, and focusing.
Introduction to React Native Pressable Component
The Button component is quite limited in terms of look and feel. If the button doesn’t meet your app design, you can build your button using the Pressable
component.
Here are the steps for using the Pressable
component:
First, import the Pressable
component from react-native
library:
import { Pressable } from 'react-native';
Code language: JavaScript (javascript)
Second, use the Pressable
component in your app:
<Pressable onPress={handlePress}>
<Text>Button</Text>
</Pressable>
Code language: JavaScript (javascript)
The Pressable
has the following events:
onPressIn
triggers when you start the press gesture.
After the onPressIn
event:
- If you remove your finger, the
Pressable
component will trigger theonPressOut
followed by theonPress
event. - If you leave your finger longer than 500 milliseconds before removing it, the
Pressable
will triggeronLongPress
event followed by theonPressOut
event.
The following picture
The following example shows how to use the Pressable
component to create a custom button:
import { StyleSheet, Text, View, Pressable, Alert } from 'react-native';
const App = () => {
const handlePress = () => {
Alert.alert('Pressed!');
}
return (
<View style={styles.container}>
<Pressable style={styles.button} onPress={handlePress}>
<Text style={styles.buttonText}>Button</Text>
</Pressable>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
paddingVertical: 8,
paddingHorizontal: 16,
borderRadius: 332,
minWidth: 100,
alignItems: 'center',
backgroundColor: '#111',
},
buttonText: {
color: '#fff',
fontSize: 16
},
});
export default App;
Code language: JavaScript (javascript)
How it works.
First, import the Pressable component with other components from react-native
library:
import { StyleSheet, Text, View, Pressable, Alert } from 'react-native';
Code language: JavaScript (javascript)
Second, create a custom button using the Pressable and Text components:
<View style={styles.container}>
<Pressable style={styles.button} onPress={handlePress}>
<Text style={styles.buttonText}>Button</Text>
</Pressable>
</View>
Code language: JavaScript (javascript)
In the Pressable
component, assign the handlePress
function to the onPress event to handle the press event.
Third, define the handlePress
event to display an alert:
const handlePress = () => {
Alert.alert('Pressed!');
}
Code language: JavaScript (javascript)
When you press the button, it shows an alert with the text Pressed!
Output:
Summary
- Use the
Pressable
component to create a custom button.