Pressable
- React Native course
- Beginner
- Lesson 44/116
- 5 min
Learn advanced touch with Pressable.
Pressable
Pressable is React Native's next-generation touch component. It resembles TouchableOpacity but offers a wider range of events: onPressIn, onPressOut, onLongPress all in one component. The style prop can take a function that receives the { pressed } state.
Example: <Pressable style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}>...</Pressable>. Here pressed being true sets opacity to 0.5. This lets you fully customize the press feedback. New code recommends Pressable.
The pressed state
The function passed to Pressable's style is called with an object that has a { pressed } property. When pressed is true the button is being held. You can use this to render a different look during the press. The same idea works with onPressIn and onPressOut.
Example: style={({ pressed }) => ({ backgroundColor: pressed ? 'tomato' : 'steelblue' })}. The button turns reddish while pressed and steel blue when released. This pattern is the standard for press feedback in modern React Native code.
Practice Press feedback with Pressable
Complete the empty component. Define handlePress. Return a <Pressable onPress={handlePress} style={({ pressed }) => ({ backgroundColor: pressed ? 'tomato' : 'steelblue' })}> containing <Text style={{ color: 'white' }}>Press</Text>.
Starter code
import React from 'react';
import { Pressable, Text } from 'react-native';
export default function PressButton() {
// Add handlePress and return a Pressable
return null;
}Sample solution
import React from 'react';
import { Pressable, Text } from 'react-native';
export default function PressButton() {
const handlePress = () => {};
return (
<Pressable onPress={handlePress} style={({ pressed }) => ({ backgroundColor: pressed ? 'tomato' : 'steelblue' })}>
<Text style={{ color: 'white' }}>Press</Text>
</Pressable>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each component to its feature
| Term | Meaning |
|---|---|
Pressable |
Next-generation touch |
TouchableOpacity |
Opacity feedback |
Button |
System default look |
onLongPress |
Long-press function |
2 What can Pressable's style prop take?
<Pressable style={???}>...</Pressable>- Only an object
- Only an array
- An object or a function Correct answer
- Only a string
Explanation: Pressable style can be either an object or a function.
3 Write the pressed parameter
<Pressable style={({____}) => ({ opacity: pressed ? 0.5 : 1 })}>...</Pressable>
<Pressable style={({pressed}) => ({ opacity: pressed ? 0.5 : 1 })}>...</Pressable>
Explanation: The pressed state is passed to the style function.