Last active
October 5, 2021 16:30
-
-
Save cuongtranduc/7d8863630af9856c82f31c79274018ce to your computer and use it in GitHub Desktop.
detect a tap outside of element in React Native
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<View | |
onStartShouldSetResponder={(evt) => { | |
evt.persist(); | |
if (!isTapInsideComponent((evt.target, this.childrenRef.current))) { | |
console.log("Press outside of component"); | |
} | |
}}> | |
<View> | |
<View | |
ref={(component) => { | |
this.childrenRef = component; | |
}}> | |
<View></View> | |
<View></View> | |
</View> | |
</View> | |
// other views | |
<View></View> | |
</View>; | |
// use recursive to check if press inside that component | |
const isTapInsideComponent = (target, nestedViewRef) => { | |
if ( | |
target && | |
nestedViewRef && | |
target._nativeTag === nestedViewRef._nativeTag | |
) { | |
return true; | |
} | |
if (nestedViewRef._children && nestedViewRef._children.length > 0) { | |
for (let index = 0; index <= nestedViewRef._children.length - 1; index++) { | |
if (isTapInsideComponent(target, nestedViewRef._children[index])) { | |
return true; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment