Search code examples
javascriptreactjsreact-nativelistenerreact-native-gesture-handler

react native listen to touch event outside component


I am creating a list of swipeable view components. I want to achieve that when one swipeable is active, touched anywhere else besides this swipeable view will close the swipe. Kind of like a textInput onblur.

I think adding a listener might help here, but not exactly sure how to achieve it.

I also have a stack navigator later that will push a page on top of the list. What I am looking for is the same, once outside the view, then close the swipe.

The code is like this, to be clear.

<SafeAreaView>
  <ScrollView>
  {items.map(item => <CustomItem itemdata={item} />)}
  </ScrollView>
</SafeAreaView>

With custom item component like:

import Swipeable from 'react-native-gesture-handler/Swipeable';

....//React component stuff

render() {
  return (
  <Swipeable
    friction={2}
    overshootRight={false}
    renderRightActions={this.renderRight}
  >
    <View> 
    .....
    </View>
  </Swipeable>
  );
}


Solution

  • Next to your component, add TouchableOpacity that takes rest of display screen


    render() {
     return (
          <>
           <TouchableOpacity style={{flex: 1, height: "100%", width:"100%"}} onPress={()=>yourOutsdieClickAction()} />
           <Swipeable
              friction={2}
              overshootRight={false}
              renderRightActions={this.renderRight}
            >
            <View> 
            .....
            </View>
           </Swipeable>
          </>
          );
      }