Pages

Saturday, November 28, 2015

React Native Tip: TouchableOpacity supports multiple children

React Native's TouchableOpacity used to require a single child element. To attach a touch event handler to multiple components, you had to first wrap them inside a container <View>:
// Old way
<TouchableOpacity>
  <View>
    <Image ... />
    <Text>...</Text>
  </View>
</TouchableOpacity>
It wasn't documented anywhere, but one bonus effect of commit 725053a is that TouchableOpacity now has an Animated.View root which supports multiple children. So if you've upgraded to React Native 0.14.0 or higher, you can now get rid of the container view when using TouchableOpacity:
// New way
<TouchableOpacity>
  <Image ... />
  <Text>...</Text>
</TouchableOpacity>
TouchableHighlight and TouchableWithoutFeedback still require a single child as of RN 0.16.0, though I would normally avoid using them anyway — TouchableHighlight often creates undesirable artifacts, and TouchableWithoutFeedback leads to a poor user experience when used alone.