Skip to content

Instantly share code, notes, and snippets.

@cuongtranduc
Last active October 5, 2021 16:30
Show Gist options
  • Save cuongtranduc/7d8863630af9856c82f31c79274018ce to your computer and use it in GitHub Desktop.
Save cuongtranduc/7d8863630af9856c82f31c79274018ce to your computer and use it in GitHub Desktop.
detect a tap outside of element in React Native
<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