RANVIR GORAI
RANVIR GORAI

Reputation: 1286

How to implement, React Native Drag-n-Drop

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.

Upvotes: 3

Views: 4761

Answers (1)

Crysfel
Crysfel

Reputation: 8158

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

Upvotes: 5

Related Questions