Skip to main content

Usage

import { useSwipe } from "@servicetitan/anvil2";

function SwipeableCard({ onDismiss }) {
  const { onTouchStart, onTouchMove, onTouchEnd, direction } = useSwipe(
    (dir) => {
      if (dir === "left") {
        onDismiss();
      }
    }
  );

  return (
    <div
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
    >
      Swipe left to dismiss
    </div>
  );
}

Parameters

ParameterTypeDescription
func(direction: string | null) => voidOptional callback when swipe is detected

Return Value

PropertyTypeDescription
onTouchStart(e: TouchEvent) => voidTouch start event handler
onTouchMove(e: TouchEvent) => voidTouch move event handler
onTouchEnd(e: TouchEvent) => voidTouch end event handler
direction"left" | "right" | nullCurrent swipe direction

Features

  • Minimum swipe distance threshold (50px) to prevent false positives
  • Detects both left and right swipes
  • Provides touch event handlers for easy integration

Examples

Dismissible Card

function DismissibleCard({ id, onDismiss }) {
  const { onTouchStart, onTouchMove, onTouchEnd } = useSwipe((direction) => {
    if (direction === "left" || direction === "right") {
      onDismiss(id);
    }
  });

  return (
    <Card
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
    >
      <Text>Swipe to dismiss</Text>
    </Card>
  );
}
function ImageCarousel({ images }) {
  const [currentIndex, setCurrentIndex] = useState(0);

  const { onTouchStart, onTouchMove, onTouchEnd } = useSwipe((direction) => {
    if (direction === "left" && currentIndex < images.length - 1) {
      setCurrentIndex((i) => i + 1);
    } else if (direction === "right" && currentIndex > 0) {
      setCurrentIndex((i) => i - 1);
    }
  });

  return (
    <div
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
    >
      <img src={images[currentIndex]} alt={`Slide ${currentIndex + 1}`} />
    </div>
  );
}

Technical Details

  • Minimum swipe distance: 50 pixels
  • Directions detected: "left", "right", or null (if swipe distance is insufficient)
  • The hook tracks touch position using clientX coordinates
  • Regular touch events (taps) are ignored due to the minimum distance threshold
Last modified on January 23, 2026