Skip to content

Instantly share code, notes, and snippets.

@AbePlays
Created April 26, 2023 01:42
Show Gist options
  • Save AbePlays/e277406edffaa6591fbbe938ddb9f2ab to your computer and use it in GitHub Desktop.
Save AbePlays/e277406edffaa6591fbbe938ddb9f2ab to your computer and use it in GitHub Desktop.
import { useState, type TouchEvent } from 'react'
interface SwipeInput {
onSwipedLeft: () => void
onSwipedRight: () => void
}
interface SwipeOutput {
onTouchStart: (e: TouchEvent) => void
onTouchMove: (e: TouchEvent) => void
onTouchEnd: () => void
}
export default function useSwipe(input: SwipeInput): SwipeOutput {
const [touchStart, setTouchStart] = useState(0)
const [touchEnd, setTouchEnd] = useState(0)
const minSwipeDistance = 50
function onTouchStart(e: TouchEvent) {
setTouchEnd(0) // otherwise the swipe is fired even with usual touch events
setTouchStart(e.targetTouches[0].clientX)
}
const onTouchMove = (e: TouchEvent) => setTouchEnd(e.targetTouches[0].clientX)
function onTouchEnd() {
if (!touchStart || !touchEnd) return
const distance = touchStart - touchEnd
const isLeftSwipe = distance > minSwipeDistance
const isRightSwipe = distance < -minSwipeDistance
if (isLeftSwipe) {
input.onSwipedLeft()
}
if (isRightSwipe) {
input.onSwipedRight()
}
}
return {
onTouchStart,
onTouchMove,
onTouchEnd,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment