I'm currently doing a react-native project of draggable view where users can drag around and save it in a database. is there anyway to do this?
i tried using React-Native Reanimated but when i store the x and y of the view and load them up again, the position changes from the position i dragged it to.
Here's my code
const updateDraggable = async (xTrans,yTrans,id) => {
try {
const response = await axios.put(apiheader + '/draggable/edit/' + id,{x:xTrans,y:yTrans});
} catch (error) {
console.error(error);
}
};
const Dragable = props => {
const translateX = useSharedValue(props.x);
const translateY = useSharedValue(props.y);
const isGestureActive = useSharedValue(false);
const pan = Gesture.Pan()
.onStart(()=>{
isGestureActive.value = true;
})
.onChange((evt) => {
translateX.value += evt.changeX;
translateY.value += evt.changeY;
})
.onEnd(()=>{
isGestureActive.value=false;
runOnJS(updateDraggable)(translateX.value,translateX.value,props.item._id)
})
const animatedStyle = useAnimatedStyle(() => {
const zIndex = isGestureActive.value ? 1000 : 1;
return {
zIndex,
transform: [
{ translateX: translateX.value },
{ translateY: translateY.value },
],
};
});
return (
<Animated.View style={animatedStyle}>
<GestureHandlerRootView style={styles.root}>
<GestureDetector gesture={pan}>
<Animated.View><Table name={props.item} key={props.item._id} /></Animated.View>
</GestureDetector>
</GestureHandlerRootView>
</Animated.View>
);
};
Try restructuring your JSX. The GestureHandlerRootView
, as the name suggests, should be at your entry point:
export default function App() {
return <GestureHandlerRootView style={{ flex: 1 }}>{/* content */}</GestureHandlerRootView>;
}
I'd recommend taking a look at the examples in the docs from RNGH as they have a great example of a draggable component. In their example the <Animated.View>
is also inside the <GestureDetector>
instead of on the outside.
If your are sure your props.x
and props.y
are correct, I don't see an issue why it wouldn't work after these changes.