How to stop touch event propagation in React-Native

I solved this issue by wrap my press event with class method that set inner variable to true, then did the original logic, and after it finished, set again the inner variable to false. Then, you can wrap your container component event handler to check if inner variable set to true or false. for example:

<TouchableOpacity onPress={this.doSomething1}>
    <TouchableOpacity onPress={this.doSomething2}>
        <Image ... />
    </TouchableOpacity>
</TouchableOpacity>

doSomething1() {
    this.preventDefault = true;
    doSomeLogic();
    this.preventDefault = false;
}

doSomething2() {
    if(!this.preventDefault) {

    }
}

This might be new since the previous answers, but I find you can just gobble the event using another "touchable":

<TouchableOpacity onPress={this.onPressOuter}>
    <TouchableOpacity activeOpacity={1}>
        <Text>Content</Text>
    </TouchableOpacity>
</TouchableOpacity>

In this example, touching the text does not trigger onPressOuter


Add to View to catch the event propagated and stop it

  • onStartShouldSetResponder={(event) => true}
  • onTouchEnd={(e) => { e.stopPropagation(); }}
<TouchableOpacity onPress={this.doSomething1}>
  <View
   onStartShouldSetResponder={(event) => true}
   onTouchEnd={(e) => {
     e.stopPropagation();
   }}
  >
      <TouchableOpacity onPress={this.doSomething2}>
        <Image ... />
      </TouchableOpacity>
  </View>
</TouchableOpacity>

Tags:

React Native