Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect tap on the outside of the View in react native

How to detect tap on the outside of the View(View is a small one width and height are 200). For example, I have a custom View(which is like a modal) and it's visibility is controlled by state. But when clicking outside of it nothing is changed because there is no setState done for that, I need to catch users tap everywhere except inside the modal. How is that possible in React Native?

like image 491
Nikasv Avatar asked Oct 17 '17 05:10

Nikasv


1 Answers

<View
  onStartShouldSetResponder={evt => {
    evt.persist();
    if (this.childrenIds && this.childrenIds.length) {
      if (this.childrenIds.includes(evt.target)) {
        return;
      }
      console.log('Tapped outside');
    }
  }} 
>
  // popover view - we want the user to be able to tap inside here
  <View ref={component => {
   this.childrenIds = component._children[0]._children.map(el => el._nativeTag) 
  }}>
    <View>
      <Text>Option 1</Text>
      <Text>Option 2</Text>
    </View>
  </View>

  // other view - we want the popover to close when this view is tapped
  <View>
    <Text>
      Tapping in this view will trigger the console log, but tapping inside the 
      view above will not.
    </Text>
  </View>
</View>

https://www.jaygould.co.uk/2019-05-09-detecting-tap-outside-element-react-native/

I found these solution here, hope it helps

like image 82
deepak rathod Avatar answered Oct 16 '22 02:10

deepak rathod