TouchableOpacity in React Native

Learn how to use a TouchableOpacity in React Native Application

In this tutorial, we'll show you how easy it is to use a TouchableOpacity in React Native.

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.

Regular Primary Button with Opacity in React Native

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>

We hope you enjoyed this content and now better understand how to use TouchableOpacity in React Native.

Never miss a beat

Stay in the loop with our latest updates and offers - no spam, just the good stuff!