Skip to content

Instantly share code, notes, and snippets.

@agibson73
Created September 7, 2017 01:03
Show Gist options
  • Save agibson73/d59b940df8055068ad9a0278fdaf859e to your computer and use it in GitHub Desktop.
Save agibson73/d59b940df8055068ad9a0278fdaf859e to your computer and use it in GitHub Desktop.
RNDraggable
import React, { Component } from 'react';
import {
View,
PanResponder,
Animated,
} from 'react-native';
class Draggable extends Component {
constructor(props){
super(props);
this.state = {
distance : 200,
pan : new Animated.ValueXY(), //Step 1
shouldRespond : false,
};
this.panResponder = PanResponder.create({ //Step 2
onStartShouldSetPanResponder : () => true,
onPanResponderMove : Animated.event([null,{ //Step 3
dx : this.state.pan.x,
dy : this.state.pan.y,
}]),
onPanResponderRelease : (e, gesture) => {
if (Math.abs(gesture.dx) > this.state.distance || Math.abs(gesture.dy) > this.state.distance){
var toPointX = gesture.dx
var toPointY = gesture.dy
if (toPointX < 0){
toPointX = toPointX - 200
}else{
toPointX = toPointX + 200
}
if (toPointY < 0){
toPointY = toPointY - 200
}else{
toPointY = toPointY + 200
}
Animated.spring( //Step 1
this.state.pan, //Step 2
{toValue:{x:toPointX,y:toPointY}} //Step 3
).start();
return
}
Animated.spring( //Step 1
this.state.pan, //Step 2
{toValue:{x:0,y:0}} //Step 3
).start();
} //Step 4
});
}
render(){
return (
<Animated.View
{...this.panResponder.panHandlers}
style = {[this.props.style,this.getStyle()]}>
{this.props.children}
</Animated.View>
);
}
getStyle() {
return [
{
transform: [
{
translateX: this.state.pan.x
},
{
translateY: this.state.pan.y
},
{
rotate: this.state.pan.x.interpolate({inputRange: [-this.state.distance, 0, this.state.distance], outputRange: ["-30deg", "0deg", "30deg"]})
}
]
},
{
opacity: this.state.pan.x.interpolate({inputRange: [-this.state.distance, 0, this.state.distance], outputRange: [0.5, 1, 0.5]})
}
];
}
}
module.exports = Draggable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment