Created
March 27, 2020 10:47
-
-
Save kmagiera/a84a37b20afd5a019184b84378ff41d4 to your computer and use it in GitHub Desktop.
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 React, { Component } from 'react'; | |
| import { StyleSheet, View } from 'react-native'; | |
| import { PanGestureHandler, State } from 'react-native-gesture-handler'; | |
| import Animated from 'react-native-reanimated'; | |
| function Snappable() { | |
| const dragStartX = useSharedValue(0); | |
| const translateX = useSharedValue(0); | |
| const boxStyle = useAnimatedStyle( | |
| context => { | |
| return { | |
| transform: [{ translateX: context.translateX }], | |
| }; | |
| }, | |
| { translateX } | |
| ); | |
| const gestureHandlers = useGestureHandlerWorkletEvents( | |
| { | |
| onStart: (event, context) => (context.dragStartX = context.translateX), | |
| onActive: (event, context) => | |
| (context.translateX = context.dragStartX + event.translationX), | |
| onEnd: (event, context) => { | |
| const snapPoint = | |
| context.translateX + event.velocityX * 0.2 < 0 ? -100 : 100; | |
| context.translateX = withSpring(snapPoint); | |
| }, | |
| }, | |
| { translateX, dragStartX } | |
| ); | |
| return ( | |
| <PanGestureHandler maxPointers={1} minDist={10} handlers={gestureHandlers}> | |
| <Animated.View style={boxStyle}>{children}</Animated.View> | |
| </PanGestureHandler> | |
| ); | |
| } | |
| function Example() { | |
| return ( | |
| <View style={styles.container}> | |
| <Snappable> | |
| <View style={styles.box} /> | |
| </Snappable> | |
| </View> | |
| ); | |
| } | |
| const BOX_SIZE = 100; | |
| const styles = StyleSheet.create({ | |
| container: { | |
| flex: 1, | |
| justifyContent: 'center', | |
| alignItems: 'center', | |
| backgroundColor: '#F5FCFF', | |
| }, | |
| box: { | |
| width: BOX_SIZE, | |
| height: BOX_SIZE, | |
| borderColor: '#F5FCFF', | |
| alignSelf: 'center', | |
| backgroundColor: 'plum', | |
| margin: BOX_SIZE / 2, | |
| }, | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment