Recently I’ve been working on a simple React Native todo list app. For adding tasks I wrote a drag and drop animation inspired by Asana’s UI. In this post I’m going to share how I built it.
Here’s what the finished animation looks like:
So without further ado let’s get to it!
The first thing you need to do is setup the project. I suggest you use React Native CLI to do so. More on that here.
Since the functionality is pretty simple we’re only going to have one
Here’s what the initial component looks like:
Setup animation properties
Now let’s define class properties that we will need for this animation in the constructor:
panelY– stores the initial position of the card. We use it to calculate the position of the card when user releases the touch.
scrollY– stores current y coordinates of the
mainPosition– Animated.ValueXY used to perform animation when the card is dragged
Now let’s figure out a way to calculate the values for
scollY. We will use component listeners to do so:
handleOnLayoutis called when the bottom panel is rendered for the first time
handleScrollis called whenever user scrolls the
Now comes the fun part. We need to setup
PanResponder to react to user’s gestures and activate the drag animation. Add the following code below the constructor properties we defined earlier:
PanResponder will move the card along the user’s touch, then once the user releases the card it will call
this.addCard(y) will render a new card, assign touch’s Y coordinates and add it to the list of the cards.
Some of you who are familiar with animation in React Native might wonder why didn’t I just use data provided by
gesture argument, like
gesture.moveY. The reason is because I found
gesture.moveY to be inconsistent and error prone, at least for Android. Using
gesture.dy + this.panelY + this.scrollY; to calculate Y coordinates gives much better results.
Now let’s take a look at the final piece of the puzzle –
this.addCard() method. This method takes Y coordinates of new card, renders it and adds it to the list. Pretty simple:
Below is the full
And that’s it for this post! This example is simple but you can build on top of it to make your card animation more sophisticated and feature rich.
Thank you for reading!