react-nativetouchableopacity

How to prevent child View from parents's onPress


I have TouchableOpacity as follows,

 <TouchableOpacity style={{flex: 1, alignItems: center, justifyContent: 'center'}} onPress={() => parentOnPress()}>
    <View style={{height: 50, width: 50}}> 
       
    <View>
 <TouchableOpacity>

The View inside TouchableOpacity occupies small portion at center of the screen and outside of View should be the target of parent onPress and inside of the View should not be target of parent onPress. But in my case when i touch inside View parent onPress is being called.

How i can prevent child View from parent's onPress?


Solution

  • A workaround could be to replace the View with another TouchableOpacity that doesn't implement an onPress:

    <TouchableOpacity
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'black',
      }}
      onPress={() => {
        // Do something
      }}>
      <TouchableOpacity
        style={{
          height: 50,
          width: 50,
          backgroundColor: 'blue',
        }}>
        {/* Content */}
      </TouchableOpacity>
    </TouchableOpacity>
    

    I've added some background colors to make it easier to test.