{"id":12335,"date":"2025-05-14T07:45:56","date_gmt":"2025-05-14T07:45:56","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=12335"},"modified":"2025-05-15T12:27:47","modified_gmt":"2025-05-15T12:27:47","slug":"detect-swipe-left-in-react-native","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/react-native\/detect-swipe-left-in-react-native","title":{"rendered":"Detect Swipe Left in React Native"},"content":{"rendered":"<p>\u200bDetecting a left swipe gesture in React Native can be achieved through various methods, each tailored to different use cases and preferences.<\/p>\n<h3>1. Using a Custom Hook with Touch Events:<\/h3>\n<p>A straightforward method involves creating a custom hook that tracks touch positions to determine swipe direction. Here&#8217;s how you can implement it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">\r\nimport { Dimensions } from 'react-native';\r\nconst windowWidth = Dimensions.get('window').width;\r\nexport function useSwipe(onSwipeLeft ?:()=&gt;void, onSwipeRight?:()=&gt;void, rangeOffset = 4) {\r\n   let firstTouch = 0;\r\n   \/\/ Set user touch start position\r\n   function onTouchStart(e) {\r\n       firstTouch = e.nativeEvent.pageX;\r\n   }\r\n   \/\/ When touch ends, check for swipe directions\r\n   function onTouchEnd(e) {\r\n       const positionX = e.nativeEvent.pageX;\r\n       const range = windowWidth \/ rangeOffset;\r\n\r\n\r\n       if (positionX - firstTouch &gt; range) {\r\n           onSwipeRight &amp;&amp; onSwipeRight();\r\n       } else if (firstTouch - positionX &gt; range) {\r\n           onSwipeLeft &amp;&amp; onSwipeLeft();\r\n       }\r\n   }\r\n   return { onTouchStart, onTouchEnd };\r\n}\r\n<\/pre>\n<p>In your component, you can utilize this hook as follows:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">\r\nexport default function App() {\r\n const { onTouchStart, onTouchEnd } = useSwipe(\r\n   () => console.log('Swiped left'),\r\n   () => console.log('Swiped right')\r\n );\r\n return (\r\n   <ScrollView\r\n     style={{ flex: 1, backgroundColor: 'red' }}\r\n     onTouchStart={onTouchStart}\r\n     onTouchEnd={onTouchEnd}\r\n     horizontal\r\n   >\r\n   <View style={styles.container}>\r\n       <Text>Open up App.tsx to start working on your app!<\/Text>\r\n   <\/View>\r\n   <\/ScrollView>\r\n );\r\n}\r\n<\/pre>\n<p>This approach offers a clean implementation without relying on external modules.<br \/>\na custom hook to detect left and right swipe gestures within a ScrollView that has horizontal={true}. Since a horizontal ScrollView arranges its children in a row direction (flexDirection: &#8216;row&#8217;) and onSwipeLeft and onSwipeRight can detect swipe left\/right you can add your logic as you want<\/p>\n<h3>2. Utilizing the PanResponder API:<\/h3>\n<p>React Native&#8217;s PanResponder API can be employed to recognize swipe gestures. By tracking the gesture&#8217;s movement, you can determine the swipe direction. For instance, by monitoring the dx (change in x-axis position), you can detect left or right swipes.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">\r\nimport React, { useRef } from 'react';\r\nimport { View, Text, PanResponder, StyleSheet } from 'react-native';\r\n\r\nexport default function SwipeDetector() {\r\n   const panResponder = useRef(\r\n       PanResponder.create({\r\n           onStartShouldSetPanResponder: () => true,\r\n           onMoveShouldSetPanResponder: () => true,\r\n\r\n\r\n           onPanResponderRelease: (evt, gestureState) => {\r\n               const { dx } = gestureState;\r\n               __DEV__ && console.log('dx', dx);\r\n               if (dx > 50) {\r\n                   console.log('Swiped Right');\r\n               } else if (dx < -50) {\r\n                   console.log('Swiped Left');\r\n               }\r\n           },\r\n       })\r\n   ).current;\r\n   return (\r\n       <View style={styles.container} {...panResponder.panHandlers}>\r\n           <Text style={styles.text}>Swipe Left or Right<\/Text>\r\n       <\/View>\r\n   );\r\n}\r\nconst styles = StyleSheet.create({\r\n   container: {\r\n       flex: 1,\r\n       justifyContent: 'center',\r\n       alignItems: 'center',\r\n       backgroundColor: '#f0f0f0',\r\n   },\r\n   text: {\r\n       fontSize: 20,\r\n       fontWeight: 'bold',\r\n   },\r\n});\r\n<\/pre>\n<h2>How It Works:<\/h2>\n<ol>\n<li>PanResponder.create() initializes a gesture responder.<\/li>\n<li>onPanResponderRelease detects swipe movements by checking dx (horizontal displacement).<\/li>\n<li>A swipe is considered:<br \/>\n-> Right swipe if dx > 50<br \/>\n-> Left swipe if dx < -50<\/li>\n<li>panHandlers is applied to the root View to capture gestures.<\/li>\n<\/ol>\n<p>This is a lightweight, dependency-free approach to detecting swipe gestures in React Native. <\/p>\n<h3>3. Using the react-native-gesture-handler Library:<\/h3>\n<p>For more advanced gesture recognition, the <strong>react-native-gesture-handler<\/strong> library provides components like Swipeable and PanGestureHandler. These components offer enhanced performance and flexibility in handling gestures. For example, Swipeable can be used to create swipeable rows with customizable actions.<br \/>\nHere you need to install <strong>react-native-gesture-handler<\/strong> lib from npm<\/p>\n<p><strong>Here is the code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">\r\nimport React from 'react';\r\nimport { View, Text, StyleSheet } from 'react-native';\r\nimport { GestureHandlerRootView, HandlerStateChangeEvent, PanGestureHandler, PanGestureHandlerEventPayload, State } from 'react-native-gesture-handler';\r\n\r\nexport default function SwipeGesture() {\r\n   const onGestureEvent = (event: HandlerStateChangeEvent<PanGestureHandlerEventPayload>) => {\r\n       const { translationX, state } = event.nativeEvent;\r\n       if (state === State.END) {\r\n           if (translationX < -50) {\r\n               console.log('Swiped Left');\r\n           } else if (translationX > 50) {\r\n               console.log('Swiped Right');\r\n           }\r\n       }\r\n   };\r\n\r\n   return (\r\n       <GestureHandlerRootView>\r\n           <PanGestureHandler onHandlerStateChange={onGestureEvent}>\r\n               <View style={styles.container}>\r\n                   <Text style={styles.text}>Swipe Left or Right<\/Text>\r\n               <\/View>\r\n           <\/PanGestureHandler>\r\n       <\/GestureHandlerRootView>\r\n   );\r\n}\r\nconst styles = StyleSheet.create({\r\n   container: {\r\n       flex: 1,\r\n       justifyContent: 'center',\r\n       alignItems: 'center',\r\n       backgroundColor: '#f0f0f0',\r\n   },\r\n   text: {\r\n       fontSize: 20,\r\n       fontWeight: 'bold',\r\n   },\r\n});\r\n<\/pre>\n<h2>How It Works:<\/h2>\n<ol>\n<li>PanGestureHandler detects swipe gestures.<\/li>\n<li>translationX determines swipe direction:<br \/>\n -> translationX < -50 \u2192 Swiped Left\n-> translationX > 50 \u2192 Swiped Right<\/li>\n<li>State.END ensures detection happens when the gesture ends.<\/li>\n<li>This solution is efficient and smooth, making it ideal for gesture-heavy apps.<\/li>\n<\/ol>\n<h3>4. Implementing the onResponderMove Event:<\/h3>\n<p>Another method involves using the onResponderMove event to track touch movements and determine swipe direction. By setting up a responder and monitoring the touch&#8217;s movement along the x-axis, you can identify left and right swipes.\u200b<\/p>\n<p><strong>Here is the code<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">\r\nimport React, { useRef } from 'react';\r\nimport { View, Text, StyleSheet, GestureResponderEvent } from 'react-native';\r\nexport default function SwipeResponder() {\r\n   const startX = useRef(0);\r\n   const onStartShouldSetResponder = () => true;\r\n   const onResponderGrant = (event:GestureResponderEvent) => {\r\n       startX.current = event.nativeEvent.pageX;\r\n   };\r\n\r\n\r\n   const onResponderRelease = (event:GestureResponderEvent) => {\r\n       const endX = event.nativeEvent.pageX;\r\n       const diffX = endX - startX.current;\r\n\r\n\r\n       if (diffX > 50) {\r\n           console.log('Swiped Right');\r\n       } else if (diffX < -50) {\r\n           console.log('Swiped Left');\r\n       }\r\n   };\r\n   return (\r\n       <View\r\n           style={styles.container}\r\n           onStartShouldSetResponder={onStartShouldSetResponder}\r\n           onResponderGrant={onResponderGrant}\r\n           onResponderRelease={onResponderRelease}\r\n       >\r\n           <Text style={styles.text}>Swipe Left or Right 2<\/Text>\r\n       <\/View>\r\n   );\r\n}\r\nconst styles = StyleSheet.create({\r\n   container: {\r\n       flex: 1,\r\n       justifyContent: 'center',\r\n       alignItems: 'center',\r\n       backgroundColor: '#f0f0f0',\r\n   },\r\n   text: {\r\n       fontSize: 20,\r\n       fontWeight: 'bold',\r\n   },\r\n});\r\n<\/pre>\n<h2>How It Works:<\/h2>\n<ul>\n<li>onResponderGrant stores the initial touch position (startX).<\/li>\n<li>onResponderRelease calculates the swipe distance when the user lifts their finger.<\/li>\n<li>If the swipe distance is:<br \/>\n-> Greater than +50 \u2192 &#8220;Swiped Right&#8221;<br \/>\n-> Less than -50 \u2192 &#8220;Swiped Left&#8221;<\/li>\n<\/ul>\n<p>This approach is simple, lightweight, and doesn&#8217;t require extra dependencies.<\/p>\n<div class=\"qanda-read-box\"><div class=\"bg-light read-more-icon\"><img decoding=\"async\" src=\"https:\/\/assets.bacancytechnology.com\/qanda\/wp-content\/uploads\/2025\/04\/24061434\/read-txt.png\" alt=\"Also Read\"><p><\/p><h3>Also Read:<\/h3><a href=\"https:\/\/www.bacancytechnology.com\/blog\/react-native-state-management\" target=\"_blank\">React Native State Management<\/a><\/div><\/div>\n<h3>5. Using the react-native-swipe-gestures Library:<\/h3>\n<p>The react-native-swipe-gestures library simplifies the process of detecting swipe gestures by providing a <strong>GestureRecognizer <\/strong>component. This component allows you to specify handlers for different swipe directions, including left swipes<br \/>\nHere you need to install react-native-swipe-gestures from npm<\/p>\n<p><strong>Here is code<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">\r\nimport React from 'react';\r\nimport { View, Text, StyleSheet } from 'react-native';\r\nimport GestureRecognizer from 'react-native-swipe-gestures';\r\n\r\nexport default function SwipeGestureComponent() {\r\n    const onSwipeLeft = () => {\r\n        console.log('Swiped Left');\r\n    };\r\n\r\n    const onSwipeRight = () => {\r\n        console.log('Swiped Right');\r\n    };\r\n\r\n    const swipeConfig = {\r\n        velocityThreshold: 0.3,\r\n        directionalOffsetThreshold: 80,\r\n    };\r\n\r\n    return (\r\n        <GestureRecognizer\r\n            onSwipeLeft={onSwipeLeft}\r\n            onSwipeRight={onSwipeRight}\r\n            config={swipeConfig}\r\n            style={styles.container}\r\n        >\r\n            <Text style={styles.text}>Swipe Left or Right<\/Text>\r\n        <\/GestureRecognizer>\r\n    );\r\n}\r\nconst styles = StyleSheet.create({\r\n    container: {\r\n        flex: 1,\r\n        justifyContent: 'center',\r\n        alignItems: 'center',\r\n        backgroundColor: '#f0f0f0',\r\n    },\r\n    text: {\r\n        fontSize: 20,\r\n        fontWeight: 'bold',\r\n    },\r\n});\r\n<\/pre>\n<h2>How It Works:<\/h2>\n<ol>\n<li>GestureRecognizer detects swipe gestures.<\/li>\n<li>onSwipeLeft triggers when a left swipe is detected.<\/li>\n<li>\nonSwipeRight triggers when a right swipe is detected.<\/li>\n<li>swipeConfig sets sensitivity:<br \/>\n-> velocityThreshold \u2192 Minimum swipe speed required.<br \/>\n-> directionalOffsetThreshold \u2192 Controls swipe accuracy.<\/li>\n<\/ol>\n<p>This method is quick, easy, and requires minimal setup.<\/p>\n<h2>Conclusion:<\/h2>\n<p>Each of these methods offers a viable solution for detecting left swipe gestures in React Native. The choice of approach depends on your project&#8217;s specific requirements and whether you prefer to use external libraries or stick with built-in APIs.<\/p>\n<p>The first four solutions are supported across all React Native frameworks, including Expo Go. However, the last solution (using react-native-swipe-gestures) works only in bare React Native projects and is not compatible with Expo Go.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u200bDetecting a left swipe gesture in React Native can be achieved through various methods, each tailored to different use cases and preferences. 1. Using a Custom Hook with Touch Events: A straightforward method involves creating a custom hook that tracks touch positions to determine swipe direction. Here&#8217;s how you can implement it: import { Dimensions [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12336,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[14],"tags":[],"class_list":["post-12335","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-native"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/12335"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=12335"}],"version-history":[{"count":17,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/12335\/revisions"}],"predecessor-version":[{"id":12373,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/12335\/revisions\/12373"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/12336"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=12335"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=12335"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=12335"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}