React Native
TouchableOpacity
Learn touch feedback with TouchableOpacity.
TouchableOpacity
TouchableOpacity is a flexible button shell that reduces its opacity when pressed. Unlike Button, it can host any component inside: Text, Image or View. onPress is still the tap function.
Example: <TouchableOpacity onPress={handlePress}><Text style={{ color: 'blue' }}>Continue</Text></TouchableOpacity>. When tapped the shell becomes half transparent, giving visual feedback. This component has been common for years, though new code prefers Pressable.
Custom children
TouchableOpacity gives button behavior while you keep full control of the look. You can drop a View inside and give it a background, border and padding. It is ideal for card-style buttons, icon buttons and custom-styled buttons.
Example: <TouchableOpacity onPress={handlePress}><View style={{ padding: 12, backgroundColor: 'tomato' }}><Text style={{ color: 'white' }}>Delete</Text></View></TouchableOpacity>. The component has a style prop too, but styling the inner View is usually more flexible.
Exercise Write a custom button
Complete the empty component. Define handlePress. Return a <TouchableOpacity onPress={handlePress}> containing <View style={styles.btn}><Text style={styles.label}>Continue</Text></View>. btn: padding: 12, backgroundColor: 'tomato'. label: color: 'white'.
Show example solution
import React from 'react';
import { TouchableOpacity, View, Text, StyleSheet } from 'react-native';
export default function ContinueButton() {
const handlePress = () => {};
return (
<TouchableOpacity onPress={handlePress}>
<View style={styles.btn}>
<Text style={styles.label}>Continue</Text>
</View>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
btn: { padding: 12, backgroundColor: 'tomato' },
label: { color: 'white' }
});
Test yourself
-
Write the TouchableOpacity component
<____ onPress={handlePress}>
<Text>Continue</Text>
</TouchableOpacity>
Show answer
<TouchableOpacity onPress={handlePress}>
<Text>Continue</Text>
</TouchableOpacity>
-
What does TouchableOpacity do?
<TouchableOpacity onPress={press}>
<Text>Tap</Text>
</TouchableOpacity>
- It only shows text
- It reduces opacity when tapped
- Its color does not change on tap
- It does not accept children
Show answer
It reduces opacity when tapped — It reduces opacity when tapped to give feedback.
-
Match each component to its feature
- Button
- Plain text label only
- TouchableOpacity
- Opacity feedback
- title
- Button label
- onPress
- Tap function
Next lesson: Pressable