Skip to content

Instantly share code, notes, and snippets.

@Hyra
Last active February 6, 2020 19:10
Show Gist options
  • Save Hyra/83d28c26640c0dfebce0d4185306bcf8 to your computer and use it in GitHub Desktop.
Save Hyra/83d28c26640c0dfebce0d4185306bcf8 to your computer and use it in GitHub Desktop.
Getting started with the PanResponder in React Native
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
Image, // we want to use an image
PanResponder, // we want to bring in the PanResponder system
Animated // we wil be using animated value
} from 'react-native';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View,
Image // we want to use an image
} from 'react-native';
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
// Initially, set the value of x and y to 0 (the center of the screen)
onPanResponderGrant: (e, gestureState) => {
this.state.pan.setValue({x: 0, y: 0});
},
// When we drag/pan the object, set the delate to the states pan position
onPanResponderMove: Animated.event([
null, {dx: this.state.pan.x, dy: this.state.pan.y},
]),
onPanResponderRelease: (e, {vx, vy}) => {
}
});
}
onPanResponderGrant: (e, gestureState) => {
// Set the initial value to the current state
this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
this.state.pan.setValue({x: 0, y: 0});
},
onPanResponderRelease: (e, {vx, vy}) => {
// Flatten the offset to avoid erratic behavior
this.state.pan.flattenOffset();
}
render() {
// Destructure the value of pan from the state
let { pan } = this.state;
// Calculate the x and y transform from the pan value
let [translateX, translateY] = [pan.x, pan.y];
// Calculate the transform property and set it as a value for our style which we add below to the Animated.View component
let imageStyle = {transform: [{translateX}, {translateY}]};
return (
<View style={styles.container}>
<Animated.View style={imageStyle} {...this._panResponder.panHandlers}>
<Image source={require('./assets/panresponder.png')} />
</Animated.View>
</View>
);
}
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY()
};
}
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => { // Some comment
},
onPanResponderMove: Animated.event([
]),
onPanResponderRelease: (e, {vx, vy}) => {
}
});
}
render() {
return (
<View style={styles.container}>
<Animated.View {...this._panResponder.panHandlers}>
<Image source={require('./assets/panresponder.png')} />
</Animated.View>
</View>
);
}
render() {
return (
<View style={styles.container}>
<Image source={require('./assets/panresponder.png')} />
</View>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment