Skip to content

Drag a card with Gesture Handler

This tutorial builds a card that you can drag in an Expo app. A pan gesture from react-native-gesture-handler 3.3.0 moves the card with the pointer, and when the drag ends, react-native-reanimated 4.7.1 animates the card back to where it started. The tests drive the gesture with Gesture Handler's test controller, and the screenshot script drags the card with a real mouse in the web export.

A blue card with the text "Drag me", at rest in the middle of the screen

The example is an Expo project. Its own files are App.tsx, src/DragCard.tsx and __tests__/DragCard.test.tsx, plus a Jest setup file.

The card

src/DragCard.tsx
import { StyleSheet, Text, View } from 'react-native';
import { GestureDetector, usePanGesture } from 'react-native-gesture-handler';
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';

// How long the card takes to return to its start, in milliseconds.
const RETURN_DURATION = 300;

export function DragCard() {
  // How far the card is from its start, in px.
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);

  const pan = usePanGesture({
    testID: 'card-pan',
    // While the gesture is active, the card follows the pointer by the
    // gesture's translation.
    onUpdate: (e) => {
      translateX.value = e.translationX;
      translateY.value = e.translationY;
    },
    // When the drag ends, the card animates back to its start.
    onDeactivate: () => {
      translateX.value = withTiming(0, { duration: RETURN_DURATION });
      translateY.value = withTiming(0, { duration: RETURN_DURATION });
    },
  });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }, { translateY: translateY.value }],
  }));

  return (
    <View style={styles.screen}>
      <GestureDetector gesture={pan}>
        <Animated.View testID="card" style={[styles.card, animatedStyle]}>
          <Text style={styles.text}>Drag me</Text>
        </Animated.View>
      </GestureDetector>
    </View>
  );
}

const styles = StyleSheet.create({
  screen: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#eef0f3' },
  card: {
    width: 160,
    height: 120,
    borderRadius: 16,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#2563eb',
  },
  text: { fontSize: 20, fontWeight: '600', color: '#fff' },
});

DragCard keeps the card's offset from its start in two shared values, translateX and translateY, both 0 at first.

usePanGesture creates the pan gesture from one config object:

  • onUpdate runs while the gesture is active and copies the event's translationX and translationY into the shared values;
  • onDeactivate runs when the gesture ends and animates both values back to 0 with withTiming, over RETURN_DURATION, 300 ms;
  • testID: 'card-pan' names the gesture, so the tests can find it.

Gesture Handler 3 renamed some callbacks to match the gesture's states: as the post Gesture Handler 3.0 brings a hook-based API and drops the legacy architecture says, onDeactivate is the new name for onEnd.

useAnimatedStyle turns the two shared values into a transform with translateX and translateY. GestureDetector attaches the gesture to the Animated.View that has that style, and the view's testID, card, lets the tests find it.

Why shared values here

The tutorial Animate a toggle with Reanimated CSS transitions uses no shared values, because its animation follows a change of state. This card follows the pointer instead: each update of the gesture writes the shared values directly. The post Reanimated 4 is stable with CSS animations and transitions says that worklets and shared values remain the recommended tools for cases such as gesture-driven animations.

The app

App.tsx
import { StatusBar } from 'expo-status-bar';
import { StyleSheet } from 'react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';

import { DragCard } from './src/DragCard';

export default function App() {
  return (
    // Gesture Handler's docs ask for GestureHandlerRootView around the app's
    // main component, so it wraps the whole app.
    <GestureHandlerRootView style={styles.container}>
      <SafeAreaProvider>
        <SafeAreaView style={styles.container}>
          <DragCard />
          <StatusBar style="auto" />
        </SafeAreaView>
      </SafeAreaProvider>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
});

App wraps the screen in GestureHandlerRootView, with flex: 1, then in SafeAreaProvider and SafeAreaView, from react-native-safe-area-context.

The same card, moved right and down during a drag

Both screenshots show the web export. The second was taken during a drag with the mouse, with the button still down.

The tests

__tests__/DragCard.test.tsx
import { render, screen } from '@testing-library/react-native';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { createGestureController, getByGestureTestId } from 'react-native-gesture-handler/jest-utils';

import { DragCard } from '../src/DragCard';

// Jest's fake timers drive the animation frames.
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());

// The card is rendered inside GestureHandlerRootView, as App.tsx renders it.
function renderCard() {
  return render(
    <GestureHandlerRootView>
      <DragCard />
    </GestureHandlerRootView>,
  );
}

// The controller calls the pan gesture's callbacks one lifecycle step at a
// time. It does not generate touches.
function controlPan() {
  return createGestureController(getByGestureTestId('card-pan'));
}

test('the card renders with its text', async () => {
  await renderCard();

  expect(screen.getByTestId('card')).toBeOnTheScreen();
  expect(screen.getByText('Drag me')).toBeOnTheScreen();
});

test('the card follows the drag', async () => {
  await renderCard();
  const card = screen.getByTestId('card');
  const pan = controlPan();

  pan.begin();
  pan.activate();
  pan.update({ translationX: 80, translationY: 40 });
  // The animated style updates on the next frame, 17 ms at 60 fps.
  jest.advanceTimersByTime(17);

  expect(card).toHaveAnimatedStyle({ transform: [{ translateX: 80 }, { translateY: 40 }] });
});

test('the card returns to its start 300 ms after the drag ends', async () => {
  await renderCard();
  const card = screen.getByTestId('card');
  const pan = controlPan();

  pan.begin();
  pan.activate();
  pan.update({ translationX: 80, translationY: 40 });
  pan.end();
  jest.advanceTimersByTime(300);

  expect(card).toHaveAnimatedStyle({ transform: [{ translateX: 0 }, { translateY: 0 }] });
});

The tests render DragCard inside GestureHandlerRootView, as App does, and drive the gesture without touches. getByGestureTestId finds the gesture by its testID, and createGestureController, from react-native-gesture-handler/jest-utils, calls its callbacks one lifecycle step at a time: begin, activate, update and end. Reanimated's toHaveAnimatedStyle matcher reads the card's animated style, and Jest's fake timers move time forward.

The three tests check that:

  • the card renders, with "Drag me";
  • one frame after an update with a translation of 80 and 40, the card's style has translateX: 80 and translateY: 40;
  • 300 ms after the gesture ends, both are back at 0.

They check the callbacks and the style they produce, not how the card responds to a real touch.

jest-setup.js
// Worklets' mock, as its "Testing with Jest" guide recommends.
jest.mock('react-native-worklets', () => require('react-native-worklets/lib/module/mock'));
// Reanimated's Jest matchers, such as toHaveAnimatedStyle, as its "Testing with Jest" guide documents.
require('react-native-reanimated').setUpTests();

The example's Jest setup file replaces react-native-worklets with the Jest mock that Worklets documents, and adds Reanimated's matchers with setUpTests. For TypeScript, reanimated-jest.d.ts references the file where Reanimated declares the matcher's type, which its package types don't load.

The drag check

The screenshot script checks the drag with real input: it opens the example's web export in Chromium, through Playwright, and drags the card with the mouse. The card starts following once the gesture activates, after the pointer has moved a short distance, so the script presses on the card's center and first moves the pointer a short way. Then, with the button still down, it moves the pointer a further 100 px right and 60 px down. The script fails unless:

  • over that second move, the card moved 100 px right and 60 px down, within 2 px each way: once the pan gesture is active, the card moves exactly as far as the pointer;
  • after the release, the card's left edge, recorded on every animation frame for 600 ms, passes between the dragged position and the start, and ends back at the start, within 1 px.

Verified with Expo SDK 58 (React Native 0.88.1): type-checked, tested with Jest and React Native Testing Library, and exported for web.

Full example: reactnative/examples/drag-card