Reading Gestures with PanResponder

+15 Mana ✨

The raw responder props hand you one touch event at a time, so tracking how far and how fast a finger moved means storing start positions and timestamps yourself, and two fingers on screen make that harder still. PanResponder, exported from react-native, wraps those props and reconciles several touches into a single gesture: a one-finger drag keeps working when a second finger lands, and basic multi-touch gestures become readable. Each of its callbacks receives a gestureState with the distance and velocity already worked out.

Key terms

  • PanResponder.create: builds a PanResponder from a config object of callbacks and returns an instance.
  • panHandlers: the instance's set of plain View responder props, ready to spread onto a view.
  • gestureState: the object PanResponder passes to each callback next to the event, holding the gesture's distance, velocity and touch count.

Responder callbacks under new names

PanResponder.create takes a required config object. Its callbacks are the responder props with Responder replaced by PanResponder: onStartShouldSetPanResponder and onMoveShouldSetPanResponder with their Capture variants, onPanResponderGrant, onPanResponderReject, onPanResponderMove, onPanResponderRelease, onPanResponderTerminationRequest, onPanResponderTerminate, plus onPanResponderStart, onPanResponderEnd and onShouldBlockNativeResponder. Each one is called with (event, gestureState).

The returned instance has a panHandlers field holding the ordinary handlers (onStartShouldSetResponder, onResponderGrant, onResponderMove and the rest). Create the instance once per component with useRef(PanResponder.create({...})).current, then spread {...panResponder.panHandlers} on the View that should receive the gesture.

Three defaults decide what happens to callbacks you leave out:

  • Without onStartShouldSetPanResponder, the start question answers false, and without onMoveShouldSetPanResponder the move question answers false too. A config with only onPanResponderMove never becomes the responder, so its move callback never runs.
  • Without onPanResponderTerminationRequest, the view releases the touch whenever another view asks.
  • onShouldBlockNativeResponder returns true by default, which blocks native components from becoming the JS responder. It is only supported on Android.

What gestureState measures

The fields are all numbers:

  • dx, dy: the accumulated distance of the gesture since the touch started.
  • vx, vy: the current velocity.
  • x0, y0: the screen coordinates where the view became the responder.
  • moveX, moveY: the latest screen coordinates of the recently moved touch.
  • numberActiveTouches: how many touches are on screen.
  • stateID: a number identifying the state object.

With more than one finger down, PanResponder tracks the centroid of the recently moved touches, computed from their page coordinates. On each move it adds the change in that centroid to dx and dy, and sets vx and vy to the same change divided by the time since the last move it processed. Two fingers moving apart in opposite directions add nothing to dx, and two fingers sliding five pixels side by side add five, not ten.

When the numbers reset

gestureState is one object per PanResponder.create call, and PanResponder rewrites it as the gesture goes on:

  • A gesture starts from zero: the state is reset when a touch starts with exactly one finger on screen.
  • On grant, x0 and y0 become the current centroid and dx and dy go back to 0 before onPanResponderGrant runs. In onPanResponderMove, they hold the distance since the view became the responder.
  • On release, onPanResponderRelease gets the final state, and then every field except stateID goes back to zero. Termination does the same after onPanResponderTerminate.

dx and dy are only valid while the view is the responder. Read the numbers you need inside the callback, because a reference to gestureState kept for later will show zeros for the distance, velocity and position fields.

Release and termination mean different things. onPanResponderRelease runs when the user lifts every finger while the view is the responder, which is usually a finished gesture. onPanResponderTerminate runs when another component took the touch, and the gesture should be cancelled.

A swipe to dismiss

The DismissibleBanner below slides with the finger and disappears after a long or fast swipe. Its move question waits for some horizontal travel, so a touch that barely moves is left alone:

onMoveShouldSetPanResponder: (_event, gestureState) => Math.abs(gestureState.dx) > 10

This works because PanResponder updates gestureState in the capture phase of each move, before any should-set callback reads it. On release, the banner checks both dx and vx, so a short flick dismisses it as well as a long drag. The two thresholds are this example's own choices. On termination it slides back, since a cancelled gesture should leave nothing behind.

Code Examples

tsx
import {useRef, useState} from 'react';
import {PanResponder, StyleSheet, Text, View} from 'react-native';

// Thresholds chosen for this example
const DISMISS_DISTANCE = 120;
const DISMISS_VELOCITY = 0.5;

export function DismissibleBanner({message}: {message: string}) {
  const [dismissed, setDismissed] = useState(false);
  const [offsetX, setOffsetX] = useState(0);

  const panResponder = useRef(
    PanResponder.create({
      onMoveShouldSetPanResponder: (_event, gestureState) =>
        Math.abs(gestureState.dx) > 10,
      onPanResponderMove: (_event, gestureState) => {
        setOffsetX(gestureState.dx);
      },
      onPanResponderRelease: (_event, gestureState) => {
        if (
          Math.abs(gestureState.dx) > DISMISS_DISTANCE ||
          Math.abs(gestureState.vx) > DISMISS_VELOCITY
        ) {
          setDismissed(true);
        } else {
          setOffsetX(0);
        }
      },
      onPanResponderTerminate: () => {
        setOffsetX(0);
      },
    }),
  ).current;

  if (dismissed) {
    return null;
  }

  return (
    <View
      style={[styles.banner, {transform: [{translateX: offsetX}]}]}
      {...panResponder.panHandlers}>
      <Text>{message}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  banner: {
    padding: 16,
    borderRadius: 12,
    backgroundColor: '#fde68a',
  },
});
✓ Completed