What is the TouchableOpacity?
TouchableOpacity
is one of the touchable components in React Native that are broadly used for registering touch
or press
events on views (such as buttons or cards).
This component fades out when pressed and fades back in when released.
TouchableOpacity
wraps children in an Animated.View
to control the opacity, which is added the view hierarchy. Be aware that this can shift the layout of your application.
import { TouchableOpacity, Text } from 'react-native';
<TouchableOpacity onPress={() => console.log('Button pressed')}>
<Text>Press Button</Text>
</TouchableOpacity>
Styling TouchableOpacity
Similar to a View
component, TouchableOpacity
can be styled using the style
property.
In this example we will make a regular primary button using TouchableOpacity
. This and many other Pre-Built React Native Components can be found in our collection.
import { TouchableOpacity, Text } from 'react-native';
<TouchableOpacity style={styles.button}>
<Text style={styles.buttonText}>Press Button</Text>
</TouchableOpacity>
const styles = StyleSheet.create({
button: {
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8,
paddingVertical: 8,
paddingHorizontal: 16,
borderWidth: 1,
backgroundColor: '#0569FF',
borderColor: '#0569FF',
},
buttonText: {
fontSize: 17,
lineHeight: 24,
fontWeight: '600',
color: '#fff',
}
})
Changing the opacity
You can use activeOpacity
to change the opacity of the TouchableOpacity
when it is active. Defaults to 0.2
import { TouchableOpacity, Text } from 'react-native';
<TouchableOpacity activeOpacity={0.6}>
<Text>Press Button</Text>
</TouchableOpacity>