Back to Playground
Interaction

Touch Gesture Recognition

Recognize swipe, pinch, and rotate gestures on touch devices with custom gesture handlers.

JavaScriptTouch EventsMobile

Demo coming soon...

Code

const useGesture = (ref) => {
  const [gesture, setGesture] = useState(null)
  
  useEffect(() => {
    let startX, startY
    
    const handleTouchStart = (e) => {
      startX = e.touches[0].clientX
      startY = e.touches[0].clientY
    }
    
    const handleTouchEnd = (e) => {
      const endX = e.changedTouches[0].clientX
      const endY = e.changedTouches[0].clientY
      
      const diffX = endX - startX
      const diffY = endY - startY
      
      if (Math.abs(diffX) > Math.abs(diffY)) {
        setGesture(diffX > 0 ? 'swipe-right' : 'swipe-left')
      } else {
        setGesture(diffY > 0 ? 'swipe-down' : 'swipe-up')
      }
    }
    
    const el = ref.current
    el?.addEventListener('touchstart', handleTouchStart)
    el?.addEventListener('touchend', handleTouchEnd)
    
    return () => {
      el?.removeEventListener('touchstart', handleTouchStart)
      el?.removeEventListener('touchend', handleTouchEnd)
    }
  }, [ref])
  
  return gesture
}