I'm currently developing a React app and I want to detect swipe events (left, right) on a div
element (on mobile devices).
How do I achieve this without any additional libraries?
This code detects left and right swipe events, without having any impact on usual touch events.
const [touchStart, setTouchStart] = useState(null)
const [touchEnd, setTouchEnd] = useState(null)
// the required distance between touchStart and touchEnd to be detected as a swipe
const minSwipeDistance = 50
const onTouchStart = (e) => {
setTouchEnd(null) // otherwise the swipe is fired even with usual touch events
setTouchStart(e.targetTouches[0].clientX)
}
const onTouchMove = (e) => setTouchEnd(e.targetTouches[0].clientX)
const onTouchEnd = () => {
if (!touchStart || !touchEnd) return
const distance = touchStart - touchEnd
const isLeftSwipe = distance > minSwipeDistance
const isRightSwipe = distance < -minSwipeDistance
if (isLeftSwipe || isRightSwipe) console.log('swipe', isLeftSwipe ? 'left' : 'right')
// add your conditional logic here
}
<div onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd}/>
If you need to detect vertical swipes as well (up and down), you can use e.targetTouches[0].clientY
(see docs) in a similar manner.