Skip to content

Instantly share code, notes, and snippets.

@jmmarco
Last active December 2, 2021 08:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmmarco/e6e8c5862be492ab871c82a078bc684c to your computer and use it in GitHub Desktop.
Save jmmarco/e6e8c5862be492ab871c82a078bc684c to your computer and use it in GitHub Desktop.
React Native using PanResponder and ref's
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