PanResponder
- React Native course
- Intermediate
- Lesson 76/116
- 5 min
Learn touch gestures with PanResponder.
PanResponder
PanResponder is a helper that handles touch and drag gestures. It binds to a component and maps gesture events to functions. It works with callbacks like onMoveShouldSetPanResponder, onPanResponderMove and onPanResponderRelease.
It is created with PanResponder.create({...}); the returned object is spread onto the component as {...panResponder.panHandlers}. The component then recognises gestures. This way complex touch interactions take little code.
PanResponder.create
PanResponder.create takes an object whose keys are callbacks. For example onMoveShouldSetPanResponder: () => true starts the gesture, and onPanResponderMove is called during the drag. Each callback represents a different phase of the gesture.
The result is held as const pan = PanResponder.create({...}); {...pan.panHandlers} is spread onto a View. That View then captures gestures.
Practice Bind a PanResponder to a View
Create a PanResponder: const pan = PanResponder.create({ onMoveShouldSetPanResponder: () => true }). Then return <View {...pan.panHandlers} />.
Starter code
import React from 'react';
import { PanResponder, View } from 'react-native';
export default function Drag() {
// Create a PanResponder and spread it onto the View
return <View />;
}Sample solution
import React from 'react';
import { PanResponder, View } from 'react-native';
export default function Drag() {
const pan = PanResponder.create({
onMoveShouldSetPanResponder: () => true,
});
return <View {...pan.panHandlers} />;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does PanResponder do?
- Draws a list
- Changes color
- Fetches data
- Handles touch gestures Correct answer
Explanation: PanResponder handles touch and drag gestures.
2 Create a PanResponder
const pan = ____.create({ onMoveShouldSetPanResponder: () => true });
const pan = PanResponder.create({ onMoveShouldSetPanResponder: () => true });
Explanation: PanResponder.create creates the gesture helper.
3 PanResponder concepts
| Term | Meaning |
|---|---|
PanResponder |
Gesture helper |
create |
Creates it |
panHandlers |
Spread to View |
onPanResponderMove |
During drag |