# useSwipe

Calls `onSwipe` with `'left'`, `'right'`, `'up'`, or `'down'` when the user swipes on an element, with touch, pen, or mouse. Returns a callback ref.

Uses pointer events, so one handler covers every input. The direction is the axis that moved most. Too short or too slow and it isn't a swipe.

Set CSS `touch-action` on the element so the browser doesn't take the gesture for scrolling: `pan-y` for horizontal swipes, `pan-x` for vertical, `none` for both.

## Import

```ts
import { useSwipe } from '@vincent.ri/react-tils'
// or only this hook
import { useSwipe } from '@vincent.ri/react-tils/useSwipe'
```

## Usage

```ts
const ref = useSwipe<HTMLDivElement>((direction) => {
  if (direction === 'left') next()
  if (direction === 'right') previous()
})
return <div ref={ref} style={{ touchAction: 'pan-y' }}><Slide /></div>
```

## When to use it

Swiping between carousel slides, dismissing a card or notification, or closing a drawer with a swipe.

## When not to

You need the element to follow the finger while dragging; use `useDrag`. For scrolling between items, CSS scroll snap (`scroll-snap-type`) needs no JS. Swipes must have a button or keyboard alternative.

## API

```ts
function useSwipe<T extends HTMLElement = HTMLElement>(onSwipe: (direction: SwipeDirection, event: PointerEvent) => void, options?: SwipeOptions): (element: T | null) => void
```

| Parameter | Description |
| --- | --- |
| `onSwipe` | Called with the direction and the `pointerup` event. Can change every render. |
| `options` | `threshold` and `maxDurationMs`. Optional. |

**Returns** A callback ref. Pass it to the element's `ref` prop.

### Types

```ts
export type SwipeDirection = "left" | "right" | "up" | "down";
export type SwipeOptions = {
  /** Minimum distance in pixels. Default `50`. */
  threshold?: number;
  /** Maximum duration in milliseconds; slower drags aren't swipes. Default `800`. */
  maxDurationMs?: number;
};
```

## Browser support

Works in all modern browsers.

---

388 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useSwipe.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useSwipe/
Previous: [useLongPress](https://vincentri.github.io/react-tils/hooks/useLongPress.md)
Next: [useDrag](https://vincentri.github.io/react-tils/hooks/useDrag.md)
