Last active
December 2, 2021 08:53
-
-
Save jmmarco/e6e8c5862be492ab871c82a078bc684c to your computer and use it in GitHub Desktop.
React Native using PanResponder and ref's
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { | |
Text, | |
View, | |
StyleSheet, | |
PanResponder, | |
TouchableOpacity, | |
Animated, | |
} from 'react-native'; | |
import Constants from 'expo-constants'; | |
export default function App() { | |
const [foo, setFoo] = React.useState(0); | |
const fooRef = React.useRef(); | |
React.useEffect(() => { | |
fooRef.current = foo; | |
}, [foo]); | |
const pan = React.useRef(new Animated.ValueXY()).current; | |
const panResponder = React.useRef( | |
PanResponder.create({ | |
onMoveShouldSetPanResponder: () => true, | |
onPanResponderGrant: () => { | |
pan.setOffset({ | |
x: pan.x._value, | |
y: pan.y._value, | |
}); | |
}, | |
onPanResponderMove: Animated.event([null, { dx: pan.x, dy: pan.y }], { | |
listener: event => { | |
//alert(fooRef.current); | |
console.log(fooRef.current); | |
}, | |
}), | |
onPanResponderRelease: () => { | |
pan.flattenOffset(); | |
}, | |
}) | |
).current; | |
return ( | |
<View style={styles.container}> | |
<Text style={styles.titleText}>{JSON.stringify(foo)}</Text> | |
<View style={styles.button}> | |
<TouchableOpacity onPress={() => setFoo(f => f + 1)}> | |
<Text style={{ color: '#fff' }}>PRESS HERE - FOO: {foo}</Text> | |
</TouchableOpacity> | |
</View> | |
<Animated.View | |
style={{ | |
transform: [{ translateX: pan.x }, { translateY: pan.y }], | |
}} | |
{...panResponder.panHandlers}> | |
<View {...panResponder.panHandlers} style={styles.box}> | |
<Text>FOO: {foo}</Text> | |
<Text>Try to drag me around</Text> | |
</View> | |
</Animated.View> | |
</View> | |
); | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
alignItems: 'center', | |
justifyContent: 'space-around', | |
}, | |
titleText: { | |
fontSize: 14, | |
lineHeight: 24, | |
fontWeight: 'bold', | |
}, | |
box: { | |
justifyContent: 'center', | |
alignItems: 'center', | |
height: 150, | |
width: 150, | |
backgroundColor: 'blue', | |
borderRadius: 5, | |
}, | |
button: { | |
backgroundColor: 'deepskyblue', | |
padding: 15, | |
borderRadius: 5, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment