Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement, React Native Drag-n-Drop

Tags:

react-native

I want to implement react-native drag-and-drop, to swap component on the drop. supposed there is five component on a screen once I drag it should highlight dropable element. and once it is dropped the component should be swap.

like image 211
RANVIR GORAI Avatar asked Jan 19 '26 03:01

RANVIR GORAI


1 Answers

In order to implement drag an drop you need to use the pan responders. First you need to define where are you going to store the values when the object is moving, you can set a property on the state.

state = {
    pan: new Animated.ValueXY(),
};

Then you will have to create the pan responders in componentWillMount for example:

this.panResponder = PanResponder.create({
    onStartShouldSetPanResponder : () => true,
    onPanResponderMove           : Animated.event([null,{ // <--- When moving
        dx : this.state.pan.x,
        dy : this.state.pan.y
    }]),
    onPanResponderRelease        : (e, gesture) => {} // <--- callback when dropped
});

Finally you need to set the left and top to the animated element in the render method.

<Animated.View 
    {...this.panResponder.panHandlers}  
     style={[this.state.pan.getLayout(), styles.circle]}>  
      <Text style={styles.text}>Drag me!</Text>
</Animated.View>

The this.state.pan.getLayout() returns the top and left, you need this in order to move the element around.

In order to swap the elements you need to implement the onPanResponderRelease.

For more detailed steps you can take a look at this tutorial: https://moduscreate.com/blog/animated_drag_and_drop_with_react_native

like image 188
Crysfel Avatar answered Jan 22 '26 07:01

Crysfel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!