TUT Create Click and Drag Animation in React Native

This is the tenth part of react native animation tutorial series. Here, let’s learn how to create a drag animation in react native. What I really mean is – a click and drag animation where the user can hold, drag and drop the view anywhere on the screen.

We use two APIs from React Native namely Animated and PanResponder to achieve the desired output. I already discussed the Animated API in the previous animation tutorials. PanResponder is used to manage multiple touch gestures.

First of all, set new x and y values using Animated API.

const pan = useRef(new Animated.ValueXY()).current;

Next, we create a new PanResponder instance.

const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderGrant: () => {
      pan.setOffset(pan.__getValue());
      pan.setValue({x: 0, y: 0});
    },
    onPanResponderMove: Animated.event([null, {dx: pan.x, dy: pan.y}], {
      useNativeDriver: false,
    }),
  });

We set onStartShouldSetPanResponder true and make the initial position of the view center by assigning x =0 and y=0 using onPanResponderGrant. We change the positions of the View using onPanResponderMove.

<Animated.View
        {...panResponder.panHandlers}
        style={[
          styles.circle,
          {
            transform: [{translateX: pan.x}, {translateY: pan.y}],
          },
        ]}
      />

Following is the complete react native pan responder animation example.

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

const Drag = () => {
  const pan = useRef(new Animated.ValueXY()).current;

  const panResponder = PanResponder.create({
    onStartShouldSetPanResponder: () => true,
    onPanResponderGrant: () => {
      pan.setOffset(pan.__getValue());
      pan.setValue({x: 0, y: 0});
    },
    onPanResponderMove: Animated.event([null, {dx: pan.x, dy: pan.y}], {
      useNativeDriver: false,
    }),
  });

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  circle: {
    backgroundColor: 'red',
    width: 60,
    height: 60,
    borderRadius: 30,
  },
});

export default Drag;

I hope this react native drag animation tutorial will help you.

No comments:

Post a Comment