How to Create Click and Drag Animation in React Native?

Nov 07, 2022 . Admin

In this tutorial we will go over the demonstration of animated drag and drop with react native. this example will help you create a drag and drop component in react native. if you have question about how to create click and drag animation in react native then I will give simple example with solution. I would like to share with you how to make drag and drop in react native. you will do the following things for how to create animation in react native.

In this example,We will create to drag and drop animation in react native.you can easy and simlpy to create to react native app.below's this example.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React, {Component} from 'react';
import {PanResponder, View, Animated, StyleSheet} from 'react-native';

export default class Drag extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pan: new Animated.ValueXY(),
    };
    // Initialize PanResponder
    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        this.state.pan.setOffset(this.state.pan.__getValue());
        this.state.pan.setValue({x: 0, y: 0});
      },
      onPanResponderMove: Animated.event(
        [null, {dx: this.state.pan.x, dy: this.state.pan.y}],
        {useNativeDriver: false},
      ),
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Animated.View
          {...this.panResponder.panHandlers}
          style={[
            styles.circle,
            {
              transform: [
                {translateX: this.state.pan.x},
                {translateY: this.state.pan.y},
              ],
            },
          ]}
        />
      </View>
    );
  }
}

let styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  circle: {
    backgroundColor: 'blue',
    width: 40,
    height: 40,
    borderRadius: 30,
  },
});
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native