CodeBlanks Logo Icon CodeBlanks

onPanResponderMove

Learn dragging with onPanResponderMove.

onPanResponderMove

onPanResponderMove is called whenever the finger moves while the gesture is active. Here you update the component's position. gestureState.dx and gestureState.dy give the total move since the start.

Example: onPanResponderMove: (evt, g) => setPos({ x: g.dx, y: g.dy }). Each frame the finger's new position is written to state; the component moves with the finger.

gestureState values

gestureState carries rich data about the gesture. dx, dy are the total displacement since the start; moveX, moveY are the finger's current position; vx, vy are velocity.

Most often dx and dy are used; they give the drag amount. You compute the position from these and apply it to the component.

Practice Update position on move

Create a PanResponder with onMoveShouldSetPanResponder: () => true and onPanResponderMove: (evt, g) => setPos({ x: g.dx, y: g.dy }). The pos state is defined with useState({ x: 0, y: 0 }). Return <View {...pan.panHandlers} />.

Starter code

App.js
import React, { useState } from 'react';
import { PanResponder, View } from 'react-native';

export default function Drag() {
  const [pos, setPos] = useState({ x: 0, y: 0 });
  // Add a PanResponder; update pos during the drag
  return <View />;
}

Sample solution

App.js
import React, { useState } from 'react';
import { PanResponder, View } from 'react-native';

export default function Drag() {
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const pan = PanResponder.create({
    onMoveShouldSetPanResponder: () => true,
    onPanResponderMove: (evt, g) => setPos({ x: g.dx, y: g.dy }),
  });
  return <View {...pan.panHandlers} />;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the move concepts

Term Meaning
onPanResponderMove During move
dx Horizontal move
dy Vertical move
gestureState Gesture data

2 When is onPanResponderMove called?

  • Only on release
  • On every move while active Correct answer
  • During mount
  • Never

Explanation: It is called on every finger move while the gesture is active.

3 Move callback

Question
PanResponder.create({ ____: (evt, g) => setPos({ x: g.dx, y: g.dy }) });
Answer
PanResponder.create({ onPanResponderMove: (evt, g) => setPos({ x: g.dx, y: g.dy }) });

Explanation: onPanResponderMove is called during the drag.

All lessons in Intermediate