Welcome to the final part of a three-part series on adding animations to React Native app. In this tutorial, we’ll be taking a look at how you can respond to the user’s gestures and animate the components involved in the interaction. Prerequisites To follow along with this tutorial, knowledge of React and React Native is \[…\]
Welcome to the final part of a three-part series on adding animations to React Native app. In this tutorial, we’ll be taking a look at how you can respond to the user’s gestures and animate the components involved in the interaction.
To follow along with this tutorial, knowledge of React and React Native is required and your machine should be set up for React Native development.
Going through the previous parts of this series (part 1, part 2) will be helpful but not required. Though this tutorial assumes that you know how to implement basic animations in React Native. Things like scale, rotation, and sequence animations. We will be applying those same concepts when implementing gesture animations.
In this part of the series, we’ll be looking at how to implement different kinds of gestures and how to animate them.
Here’s what you’ll be building:
You can find the full source code for this tutorial on its GitHub repo.
To follow along, you first need to clone the repo:
1git clone https://github.com/anchetaWern/RNRealworldAnimations.git
After that, switch to the part2
branch and install all the dependencies:
1cd RNRealworldAnimations 2 git checkout part2 3 npm install
Next, initialize the android
and ios
folders and then link the native modules:
1react-native upgrade 2 react-native link
Once that’s done, you should be able to run the app on your device or emulator:
1react-native run-android 2 react-native run-ios
The part2
branch contains the final output of the second part of this series. That’s where we want to start with, as each part is simply building upon the previous part.
The first gesture that we’re going to implement is drag-and-drop, and looks like this:
Before we start implementing this gesture, we first have to remove the animated header that we did on part two of the series. This is because that animation gets in the way when the user begins to drag the cards around.
To remove the animated header, open src/screens/Main.js
and remove these lines:
1import AnimatedHeader from "../components/AnimatedHeader"; 2 3 <AnimatedHeader 4 title={"Poke-Gallery"} 5 nativeScrollY={nativeScrollY} 6 onPress={this.shuffleData} 7 />
You can check the specific commit diff for the change above here. Note that there are other changes in there as well, but mind only the changes that have to do with removing the AnimatedHeader
component for now. Once that’s done, you should be able to delete the src/components/AnimatedHeader.js
file as well.
Next, update src/components/CardList.js
and convert the Animated.ScrollView
into a regular one. Since we’ll no longer be using the AnimatedHeader
, there’s no point in keeping the code for animating it on scroll:
1<ScrollView> 2 <View style={[styles.scroll_container]}> 3 <FlatList ... /> 4 </View> 5 </ScrollView>
You can check the specific commit diff here. Note that I’ve added a few props as well, but we’ll get to that later.
The gesture that we’re trying to implement is called “panning”. It is when a user drags their thumb (or any finger) across the screen in order to move things around. In this case, we want the user to be able to drag the cards around so they could drop it inside a specific drop area.
Here’s a break down of what we’ll need to do in order to implement the drag and drop:
Card
component to use the React Native’s PanResponder module. This makes it draggable across the screen.DropArea
component which will be used as a dropping point for the cards. The styles of this component will be updated based on whether a card is currently being dragged and whether it’s within the drop area.DropArea
. Then create the functions to be passed as props to the CardList
, Card
, and DropArea
components. This allows us to control them from the main screen.Before we proceed, let’s take a moment to break down what we’re trying to accomplish:
DropArea
and the card.DropArea
, we want to change the border and text color of the DropArea
to green. This indicates that the user in on-target and they can drop the card there.DropArea
, and show all the cards that were hidden.Now that that’s clear, the first step is to convert the Card
component from a functional to a class-based component. We won’t really be using state in this component, so this change is only to organize the code better. While you’re at it, also remove the code for animating the card onPressIn
and onPressOut
.
We don’t really want them to get in the way of the gesture that we’re trying to implement. Here’s what the new code structure will look like after the change. You can check the diff here:
1// src/components/Card.js 2 // imports here 3 // next: import PanResponder 4 5 export default class Card extends Component<Props> { 6 constructor() { 7 } 8 9 render() { 10 // destructure the props here 11 12 // the return code here 13 } 14 }
Next, we need to import PanResponder
module from react-native
:
1import { 2 // ..previously imported moodules here.. 3 PanResponder 4 } from "react-native";
The PanResponder
module is React Native’s way of responding to gestures such as panning, swiping, long press, and pinching.
Next, update the constructor
and initialize the animated values that we’re going to use. In this case, we want a scale and opacity animation. We’re also using a new Animated.ValueXY
, this is the animated value for controlling the card’s position on the screen:
1// src/components/Card.js 2 constructor(props) { 3 super(props); 4 5 this.pan = new Animated.ValueXY(); // for animating the card's X and Y position 6 this.scaleValue = new Animated.Value(0); // for scaling the card while the user drags it 7 this.opacityValue = new Animated.Value(2); // for making the card translucent while the user drags it 8 9 this.cardScale = this.scaleValue.interpolate({ 10 inputRange: [0, 0.5, 1], // animate to 0.5 while user is dragging, then to 1 or 0 once they let go 11 outputRange: [1, 0.5, 1] 12 }); 13 14 this.cardOpacity = this.opacityValue.interpolate({ 15 inputRange: [0, 1, 2], // default value is 2, so we'll animate backwards 16 outputRange: [0, 0.5, 1] 17 }); 18 }
Next, inside componentWillMount
, right below the prop destructuring, create a new PanResponder:
1componentWillMount() { 2 const { 3 // existing props here.. 4 } = this.props; 5 6 // add the following: 7 this.panResponder = PanResponder.create({ 8 onStartShouldSetPanResponder: () => true, 9 onMoveShouldSetPanResponder: () => true, 10 onPanResponderGrant: (e, gestureState) => { 11 // next: add code for onPanResponderGrant 12 }, 13 onPanResponderMove: (e, gesture) => { 14 15 }, 16 onPanResponderRelease: (e, gesture) => { 17 18 } 19 }); 20 }
Breaking down the code above:
onStartShouldSetPanResponder
– used for specifying whether to allow the PanResponder to respond to touch feedback. Note that we’ve simply supplied true
, but ideally, you’ll want to supply a function which contains a condition for checking whether you want to initiate the gesture or not. For example, if you have some sort of “lock” functionality that the user needs to unlock before they can move things around.onMoveShouldSetPanResponder
– for checking whether to respond to the dragging of the component where the PanResponder will be attached later on. Again, we’ve just specified true
, but if you need to check whether a specific condition returns true
, this is where you want to put it.Oddly though, even if you supply false
to all of the above or don’t supply it at all, it still works on the iOS simulator. But even if this is the case, it’s a good practice to still specify it because you never know how different devices behave in the real world.
onPanResponderGrant
– the function you supply here is executed when the PanResponder starts to recognize the user’s action as a gesture. So when the user has started to drag the card even just a little bit, the function will be executed. This is where we want to animate the card so it becomes smaller and translucent.onPanResponderMove
– executed while the user drags their finger across the screen. This is where you want to execute the animation for changing the card’s position. This is also where you want to check whether the card is within the drop area or not so you can animate the styling of the DropArea
component.onPanResponderRelease
– executed when the user finishes the gesture. This is when their finger lets go of the screen. Here, you also need to check whether the card is within the drop area or not so you can animate it accordingly.In my opinion, those are the most common functions that you will want to supply. But there are others available.
Now, let’s add the code for each of the gesture lifecycle functions. For onPanResponderGrant
, we’ll animate the scaleValue
and opacityValue
at the same time. Below it, we have a function called toggleDropArea
which is used to update the state so it hides all the other cards and shows the DropArea
component.
We’ll be supplying this function later from the Main screen, then down to the CardList, and finally to each of the Card components. For now, don’t forget to destructure it from this.props
:
1// src/components/Card.js 2 onPanResponderGrant: (e, gestureState) => { 3 Animated.parallel([ 4 Animated.timing(this.scaleValue, { 5 toValue: 0.5, // scale it down to half its original size 6 duration: 250, 7 easing: Easing.linear, 8 useNativeDriver: true 9 }), 10 Animated.timing(this.opacityValue, { 11 toValue: 1, 12 duration: 250, 13 easing: Easing.linear, 14 useNativeDriver: true 15 }) 16 ]).start(); 17 18 toggleDropArea(true, item); // supplied from the src/screens/Main.js down to src/components/CardList and then here. Accepts the drop area's visibility and the item to exclude from being hidden 19 } 20 // next: add code for onPanResponderMove
Next is onPanResponderMove
. Here, we do the same thing we did on part two of this series when we implemented the animated header. That is, to use Animated.event
to map the card’s current position to this.pan
. This allows us to animate the card’s position as the user drags it around. dx
and dy
are the accumulated distance in the X and Y position since the gesture started. We use those as the values for this.pan.x
and this.pan.y
:
1onPanResponderMove: (e, gesture) => { 2 Animated.event([null, { dx: this.pan.x, dy: this.pan.y }])(e, gesture); 3 if (isDropArea(gesture)) { 4 targetDropArea(true); 5 } else { 6 targetDropArea(false); 7 } 8 }, 9 // next: add code for onPanResponderRelease
Note that Animated.event
returns a function, that’s why we’re supplying e
(event), and gesture
as arguments to the function it returns.
On onPanResponderRelease
, we check whether the card is within the drop area by using the isDropArea
function. Again, this function will be passed as props from the Main screen just like the toggleDropArea
function. If the card is within the drop area, we set its opacity down to zero so it’s no longer visible. Then we call the removePokemon
function (passed as props from the Main screen) to remove it from the state:
1onPanResponderRelease: (e, gesture) => { 2 toggleDropArea(false, item); // hide the drop area and show the hidden cards 3 4 if (isDropArea(gesture)) { 5 Animated.timing(this.opacityValue, { 6 toValue: 0, 7 duration: 500, 8 useNativeDriver: true 9 }).start(() => {}); 10 11 removePokemon(item); // remove the pokemon from the state 12 } else { 13 // next: add code for animating the card back to its original position 14 } 15 }
Next, animate the card to its original position. Here, we simply do the animation we declared on onPanResponderGrant
in reverse. But the most important part here is animating this.pan
. Since we’re working with a vector value, we specify an object containing the separate values for the x
and y
position. It’s a good thing, we can simply specify 0
as the value for both to bring them back to their original position. No need to calculate the card’s position or anything complex like that:
1// src/components/Card.js 2 Animated.parallel([ 3 Animated.timing(this.scaleValue, { 4 toValue: 1, 5 duration: 250, 6 easing: Easing.linear, 7 useNativeDriver: true 8 }), 9 Animated.timing(this.opacityValue, { 10 toValue: 2, 11 duration: 250, 12 easing: Easing.linear, 13 useNativeDriver: true 14 }), 15 Animated.spring(this.pan, { 16 toValue: { x: 0, y: 0 }, 17 friction: 5, 18 useNativeDriver: true 19 }) 20 ]).start();
Next, let’s take a look at the render
method. Here, everything else is still the same except for the animated styles we supply and the Animated.View
in place of the TouchableWithoutFeedback
that we previously had. The most important part that allows the component to be moved is the transform
styles which correspond to x
and y
values of this.pan
, and the supplying of the PanResponder
props ({...this.panResponder.panHandlers}
):
1// src/components/Card.js 2 render() { 3 const { 4 item, 5 cardAction, 6 viewAction, 7 bookmarkAction, 8 shareAction 9 } = this.props; 10 11 let [translateX, translateY] = [this.pan.x, this.pan.y]; 12 13 let transformStyle = { 14 ...styles.card, 15 opacity: item.isVisible ? this.cardOpacity : 0, 16 transform: [{ translateX }, { translateY }, { scale: this.cardScale }] 17 }; 18 19 return ( 20 <Animated.View style={transformStyle} {...this.panResponder.panHandlers}> 21 ... 22 </Animated.View> 23 ); 24 }
Moreover, we’re also expecting an isVisible
property for each item
. It will be used to hide or show the card. This property is what we update when the user starts or stops the gesture.
Next, we can now move on to creating the DropArea
component. If you’ve seen the demo earlier, this is the little box that shows up in the top-right corner when the user starts the gesture. Here is the code:
1// src/components/DropArea.js 2 import React, { Component } from "react"; 3 import { View, Text, Dimensions } from "react-native"; 4 5 const DropArea = ({ dropAreaIsVisible, setDropAreaLayout, isTargeted }) => { 6 const right = dropAreaIsVisible ? 20 : -200; 7 const color = isTargeted ? "#5fba7d" : "#333"; 8 return ( 9 <View 10 style={[styles.dropArea, { right }, { borderColor: color }]} 11 onLayout={setDropAreaLayout} 12 > 13 <Text style={[styles.dropAreaText, { color }]}>Drop here</Text> 14 </View> 15 ); 16 }; 17 18 const styles = { 19 dropArea: { 20 position: "absolute", 21 top: 20, 22 right: 20, 23 width: 100, 24 height: 100, 25 backgroundColor: "#eaeaea", 26 borderWidth: 3, 27 borderStyle: "dashed", // note: doesn't work on android: https://github.com/facebook/react-native/issues/17251 28 alignItems: "center", 29 justifyContent: "center" 30 }, 31 dropAreaText: { 32 fontSize: 15 33 } 34 }; 35 36 export default DropArea;
If you inspect the code above, no animation will actually happen. All we’re doing is changing the styles based on the following boolean values coming from the props:
dropAreaIsVisible
– whether the component is visible or not.isTargeted
– whether a card is within its area.setDropAreaLayout
is a function that allows us to update the Main screen’s state of the position of the drop area in the screen. We’ll be needing that information to determine whether a card is within the drop area or not.
Next, update the Main screen. First, add the isVisible
property to each of the Pokemon:
1// src/screens/Main.js 2 const animationConfig = {...} 3 4 // add this: 5 let updated_pokemon = pokemon.map(item => { 6 item.isVisible = true; 7 return item; 8 });
Inside the component, since we’re no longer using the animated header, you now need to add value for the headerTitle
:
1// src/screens/Main.js inside navigationOptions 2 headerTitle: "Poke-Gallery",
Initialize the state:
1state = { 2 pokemon: updated_pokemon, // change pokemon to updated_pokemon 3 isDropAreaVisible: false 4 };
Inside the render
method, we render the DropArea
before the CardList
so that it has lower z-index
than any of the other cards. This way, the cards are always on top of the card list when the user drags it. Don’t forget to pass the props that we’re expecting from the DropArea
component. We’ll declare those later:
1// src/screens/Main.js 2 import DropArea from '../components/DropArea'; // add this somewhere below the react-native imports 3 4 return ( 5 <View style={styles.container}> 6 <DropArea 7 dropAreaIsVisible={this.state.isDropAreaVisible} 8 setDropAreaLayout={this.setDropAreaLayout} 9 isTargeted={this.state.isDropAreaTargeted} 10 /> 11 ..previously rendered components here 12 ..next: update CardList 13 </View> 14 );
Update the CardList
so it has the props that we’re expecting:
1<CardList 2 ...previous props here 3 scrollEnabled={!this.state.isDropAreaVisible} 4 toggleDropArea={this.toggleDropArea} 5 dropAreaIsVisible={this.state.isDropAreaVisible} 6 isDropArea={this.isDropArea} 7 targetDropArea={this.targetDropArea} 8 removePokemon={this.removePokemon} 9 />
Next, we can now add the code for the functions that we’re passing. First is the toggleDropArea
. As you’ve seen earlier, this function is called every time the user initiates and finishes the gesture. All it does is flip the isVisible
property of each item based on the isVisible
argument passed to it.
When the user initiates the gesture, isVisible
is true
. This means that the DropArea
is visible, but the rest of the cards are hidden. The item
argument passed to this function is the object containing the details of the card being dragged. So we use it to find the index of the item to be excluded from the hiding. We then update the state with the new data:
1// src/screens/Main.js 2 toggleDropArea = (isVisible, item) => { 3 if (item) { 4 let pokemon_data = [...this.state.pokemon]; 5 let new_pokemon_data = pokemon_data.map(item => { 6 item.isVisible = !isVisible; 7 return item; 8 }); 9 let index = new_pokemon_data.findIndex(itm => itm.name == item.name); 10 11 if (isVisible) { 12 new_pokemon_data[index].isVisible = true; 13 } 14 15 this.setState({ 16 isDropAreaVisible: isVisible, 17 pokemon: new_pokemon_data 18 }); 19 } 20 };
setDropAreaLayout
‘s job is to update the dropAreaLayout
to be used by the isDropArea
function:
1// src/screens/Main.js 2 setDropAreaLayout = event => { 3 this.setState({ 4 dropAreaLayout: event.nativeEvent.layout 5 }); 6 };
isDropArea
is where the logic for changing the styles of the drop area is. It’s also used to determine whether the card will be brought back to its original position or dropped in the drop area. Note that the condition below isn’t 100% fool-proof. gesture.moveX
and gesture.moveY
aren’t actually the position of the card in the screen’s context.
Instead, these are the latest screen coordinates of the recently-moved touch. Which means that the position is based on where the user touched. So if the user held on to the lower portion of the card then they have to raise the card much higher than the drop area in order to target it.
The same is true with holding on to the left side of the card. For that, they’ll have to move the card further right of the drop area in order to target it. So the safest place to touch is in the middle, right, or top:
1// src/screens/Main.js 2 isDropArea = gesture => { 3 let dropbox = this.state.dropAreaLayout; 4 return ( 5 gesture.moveY > dropbox.y + DROPAREA_MARGIN && 6 gesture.moveY < dropbox.y + dropbox.height + DROPAREA_MARGIN && 7 gesture.moveX > dropbox.x + DROPAREA_MARGIN && 8 gesture.moveX < dropbox.x + dropbox.width + DROPAREA_MARGIN 9 ); 10 };
The function above compares the position of the touch to the position of the drop area. We’re adding a DROPAREA_MARGIN
to account for the top and right margin added to the DropArea
component.
targetDropArea
updates the state so that the text and border color of the drop area is changed:
1// src/screens/Main.js 2 targetDropArea = isTargeted => { 3 this.setState({ 4 isDropAreaTargeted: isTargeted 5 }); 6 };
removePokemon
removes the dropped item from the state. This also uses LayoutAnimation to animate the rest of the cards with a spring animation after a card has been dropped:
1// src/screens/Main.js 2 removePokemon = item => { 3 let pokemon_data = [...this.state.pokemon]; 4 let index = pokemon_data.findIndex(itm => itm.name == item.name); 5 pokemon_data.splice(index, 1); 6 7 LayoutAnimation.configureNext(animationConfig); 8 9 this.setState({ 10 pokemon: pokemon_data, 11 }); 12 };
Next, update the CardList
component to accept all the props that need to be passed to the Card
component. We also need to optionally enable the ScrollView’s scrolling (scrollEnabled
prop) because it gets in the way when the user begins to drag a card. Lastly, the FlatList
also enables scrolling by default, so we disable that as well, and just rely on the ScrollView
for the scroll:
1// src/components/CardList.js 2 const CardList = ({ 3 // previous props here.. 4 scrollEnabled, 5 toggleDropArea, 6 isDropArea, 7 targetDropArea, 8 removePokemon 9 }) => { 10 return ( 11 <ScrollView scrollEnabled={scrollEnabled}> 12 <View style={[styles.scroll_container]}> 13 <FlatList 14 scrollEnabled={false} 15 ...previous props here 16 renderItem={({ item }) => { 17 <Card 18 ...previous props here 19 toggleDropArea={toggleDropArea} 20 isDropArea={isDropArea} 21 targetDropArea={targetDropArea} 22 removePokemon={removePokemon} 23 /> 24 }} 25 /> 26 </View> 27 </ScrollView> 28 ); 29 });
Also update the Card
component to accept the props passed to it by the CardList
component:
1// src/components/Card.js 2 componentWillMount() { 3 const { 4 /* previously accepted props here */ 5 toggleDropArea, 6 isDropArea, 7 targetDropArea, 8 removePokemon 9 } = this.props; 10 }
Next, update the layout settings file to export the DROPAREA_MARGIN
:
1// src/settings/layout.js 2 const DROPAREA_MARGIN = 20; 3 export { DROPAREA_MARGIN };
Lastly, update the Main screen so it uses the DROPAREA_MARGIN
:
1// src/screens/Main.js 2 import { DROPAREA_MARGIN } from "../settings/layout";
Once that’s done, you should achieve a similar output to the demo from earlier.
As you might already know, there are implementation differences between Android and iOS. And if you’ve worked with both platforms before, then you also know that React Native for Android is behind iOS. This means there are more Android-specific issues and gotchas that you might encounter when working with React Native.
This section is specifically for dealing with Android related issue when it comes to the FlatList
component. The problem with it is that changing the opacity and z-index of the Card
components while the user is dragging a card doesn’t achieve the same effect as in iOS. On Android, each row has some sort of a wrapper which wraps each of the Card
components.
This wrapper cannot be influenced by declaring a z-index for the Card
component. And even though the Card
components are currently hidden while the user is dragging, the card can’t actually be dragged outside its row because it becomes hidden as soon as you do so.
After days of looking for a solution, I gave up and decided to stick with a custom list instead.
Open, src/components/CardList.js
and convert it into a class-based component:
1export default class CardList extends Component<Props> { 2 render() { 3 const { data, scrollEnabled } = this.props; 4 5 return ( 6 <ScrollView scrollEnabled={scrollEnabled}> 7 <View style={[styles.scroll_container]}>{this.renderPairs(data)}</View> 8 </ScrollView> 9 ); 10 } 11 12 // next: add renderPairs method 13 }
The renderPairs
function returns each individual row, and it uses the renderCards
function to render the cards:
1renderPairs = data => { 2 let pairs = getPairsArray(data); 3 4 return pairs.map((pair, index) => { 5 return ( 6 <View style={styles.pair} key={index}> 7 {this.renderCards(pair)} 8 </View> 9 ); 10 }); 11 }; 12 13 // next: add renderCards function
Next, add the renderCards
method. This is responsible for rendering the individual Card
components:
1renderCards = pair => { 2 const { 3 cardAction, 4 viewAction, 5 bookmarkAction, 6 shareAction, 7 toggleDropArea, 8 isDropArea, 9 targetDropArea, 10 removePokemon 11 } = this.props; 12 13 return pair.map(item => { 14 return ( 15 <Card 16 key={item.name} 17 item={item} 18 cardAction={cardAction} 19 viewAction={viewAction} 20 bookmarkAction={bookmarkAction} 21 shareAction={shareAction} 22 toggleDropArea={toggleDropArea} 23 isDropArea={isDropArea} 24 targetDropArea={targetDropArea} 25 removePokemon={removePokemon} 26 /> 27 ); 28 }); 29 };
Outside the class, right before the styles
declaration, create a function called getPairsArray
. This function will accept an array of items and restructures it so that each row will have one pair of item:
1src/components/CardList.js 2 const getPairsArray = items => { 3 var pairs_r = []; 4 var pairs = []; 5 var count = 0; 6 items.forEach(item => { 7 count += 1; 8 pairs.push(item); 9 if (count == 2) { 10 pairs_r.push(pairs); 11 count = 0; 12 pairs = []; 13 } 14 }); 15 return pairs_r; 16 }; 17 18 const styles = { ... } // next: update styles
Don’t forget to add the styles for each pair:
1const styles = { 2 /* previously added styles here */ 3 pair: { 4 flexDirection: "row" 5 } 6 };
Once that’s done, you should now be able to drag and drop the cards in the drop area.
If you’re having problems getting it to work, you can check the specific commit here.
The next gesture that we’re going to implement is swipe, and it looks like this:
This part builds up from the drag-and-drop gesture. So the list of Pokemon you see above are the one’s that were dropped. Swiping the item to the right removes it entirely.
Let’s see what needs to be done in order to implement this:
Swiper
component where the swiping gesture will be added. These are the items that you see in the above demo.Swiper
component will be used to display the items that were dropped in the drop area.pokemon
state (the array containing the list of Pokemon) also needs to be updated so the dropped Pokemon will be removed and copied into another state (removed_pokemon
) which contains an array of Pokemon that were dropped. This is then used as the data source for the Trash screen.Let’s proceed with creating the Swiper
component. First, import all the things that we’ll need:
1// src/components/Swiper.js 2 import React, { Component } from "react"; 3 import { 4 View, 5 Image, 6 Text, 7 Dimensions, 8 Animated, 9 PanResponder 10 } from "react-native"; 11 12 const width = Dimensions.get("window").width; // for calculating the distance swiped
Next, create the component. When the user swipes an item to the right, it removes that item from the removed_pokemon
state so we need to accept the item
to be removed. We also need to pass the dismissAction
which will remove the item from the state:
1const Swiper = ({ item, dismissAction }) => { 2 3 // next: add animated values 4 5 };
Next, we initialize the animated values that we will be using. We want the items to be moved to the left or to the right (translateX
), and make it translucent (opacityValue
) as they move it:
1let translateX = new Animated.Value(0); 2 let opacityValue = new Animated.Value(0); 3 4 let cardOpacity = opacityValue.interpolate({ 5 inputRange: [0, 1], 6 outputRange: [1, 0.5] 7 }); 8 9 // next: add PanResponder code
Next, create the PanResponder:
1let panResponder = PanResponder.create({ 2 onStartShouldSetPanResponder: () => true, 3 onMoveShouldSetPanResponder: () => true, 4 onPanResponderMove: (e, gesture) => { 5 // next: add code for onPanResponderMove 6 }, 7 onPanResponderRelease: (e, { vx, dx }) => { 8 9 } 10 });
When the user begins the gesture, we map the value of dx
to the animated value translateX
. We did the same thing with the Card
component earlier. The only difference is that this time, we’re only translating the X
position. Below that, we also animate the opacityValue
. We’ve used a really low duration
value so the component will immediately turn translucent as soon as the gesture is started:
1onPanResponderMove: (e, gesture) => { 2 Animated.event([null, { dx: translateX }])(e, gesture); 3 Animated.timing(opacityValue, { 4 toValue: 1, 5 duration: 50, 6 useNativeDriver: true 7 }).start(); 8 } 9 // next: add code for onPanResponderRelease
When the user ends the gesture, we determine whether to bring the component back to its original position or animate the remaining distance all the way to the right. Luckily, the way we implement it is pretty straightforward. We compare the absolute value of dx
(the accumulated distance of the gesture in the X
axis) to half of the screen’s total width. So if the user managed to drag the component to greater than half of the screen then it means that they want to remove the item. We’re also checking if dx
is not a negative number. We only consider the gesture as valid if the user is swiping to the right. This works because dx
will have a negative value if the user swipes to the left.
As for the animated value, we simply use the screen’s width as the final value. If dx
is greater than 0
then it means they’re swiping to the right so we have a positive width
value. Otherwise, we use the negative width
:
1onPanResponderRelease: (e, { vx, dx }) => { 2 if (Math.abs(dx) >= 0.5 * width && Math.sign(dx) != -1) { 3 dismissAction(item); 4 Animated.timing(translateX, { 5 toValue: dx > 0 ? width : -width, 6 duration: 200, 7 useNativeDriver: true 8 }).start(); 9 } else { 10 // next: add code for bringing back the component to its original position 11 } 12 }
If the condition failed, we spring back the component to its original position and bring back its original opacity:
1Animated.parallel([ 2 Animated.spring(translateX, { 3 toValue: 0, 4 bounciness: 20, 5 useNativeDriver: true 6 }), 7 Animated.timing(opacityValue, { 8 toValue: 0, 9 duration: 5, 10 useNativeDriver: true 11 }) 12 ]).start();
Next, we render the actual component:
1// src/components/Swiper.js 2 return ( 3 <Animated.View 4 style={{ 5 transform: [{ translateX }], 6 opacity: cardOpacity, 7 ...styles.bar 8 }} 9 {...panResponder.panHandlers} 10 > 11 <Image source={item.pic} style={styles.thumbnail} resizeMode="contain" /> 12 <Text style={styles.name}>{item.name}</Text> 13 </Animated.View> 14 );
Here are the styles:
1const styles = { 2 bar: { 3 height: 50, 4 flexDirection: "row", 5 borderWidth: 1, 6 borderColor: "#ccc", 7 alignItems: "center", 8 marginTop: 2, 9 marginBottom: 2, 10 paddingLeft: 5 11 }, 12 thumbnail: { 13 width: 35, 14 height: 35 15 } 16 }; 17 18 export default Swiper;
The Trash screen is where the Swiper
component will be displayed. All the items that were dropped in the drop area will be displayed on this page:
1// src/screens/Trash.js 2 import React, { Component } from "react"; 3 import { View, FlatList, LayoutAnimation } from "react-native"; 4 import Swiper from "../components/Swiper"; 5 6 type Props = {}; 7 export default class Trash extends Component<Props> { 8 static navigationOptions = ({ navigation }) => { 9 return { 10 headerTitle: "Trash", 11 headerStyle: { 12 elevation: 0, 13 shadowOpacity: 0, 14 backgroundColor: "#B4A608" 15 }, 16 headerTitleStyle: { 17 color: "#FFF" 18 } 19 }; 20 }; 21 22 state = { 23 removed_pokemon: [] // array containing the items that were dropped from the Main screen 24 }; 25 26 // next: add componentDidMount 27 28 }
When the component is mounted, we call fillRemovedPokemon
. This will simply copy the contents of the removed_pokemon
that was passed as a navigation param from the Main screen over to the removed_pokemon
state of this screen. That way, this screen has its own state that we could manipulate:
1componentDidMount() { 2 this.fillRemovedPokemon(this.props.navigation.state.params.removed_pokemon); 3 }
Here’s the fillRemovedPokemon
method:
1fillRemovedPokemon = removed_pokemon => { 2 this.setState({ 3 removed_pokemon 4 }); 5 };
Next, we render the actual list:
1render() { 2 return ( 3 <View style={styles.container}> 4 {this.state.removed_pokemon && ( 5 <FlatList 6 data={this.state.removed_pokemon} 7 renderItem={({ item }) => ( 8 <Swiper item={item} dismissAction={this.dismissAction} /> 9 )} 10 keyExtractor={item => item.id.toString()} 11 /> 12 )} 13 </View> 14 ); 15 }
The dismissAction
is the one responsible for removing the items that the user wants to remove. Here, we’re using LayoutAnimation to easily update the UI once an item has been removed. In this case, we’re using it to automatically fill the empty space left by the removed item:
1// src/components/Swiper.js 2 dismissAction = item => { 3 LayoutAnimation.configureNext(LayoutAnimation.Presets.spring); 4 let removed_pokemon = [...this.state.removed_pokemon]; 5 let index = removed_pokemon.findIndex(itm => itm.name == item.name); 6 7 removed_pokemon.splice(index, 1); 8 9 this.setState({ 10 removed_pokemon 11 }); 12 };
Here are the styles:
1const styles = { 2 container: { 3 flex: 1, 4 backgroundColor: "#fff" 5 } 6 };
Next, update the src/screens/Main.js
file. First, include the IconButton
component. We’ll be using it to display a button inside the header:
1import IconButton from "../components/IconButton";
Update the navigationOptions
to include headerRight
. This allows us to render a component on the right side of the header. The navigateToTrash
method is passed as a navigation param as you’ll see later:
1static navigationOptions = ({ navigation }) => { 2 const { params } = navigation.state; // add this 3 return { 4 headerTitle: "Poke-Gallery", 5 // add this: 6 headerRight: ( 7 <IconButton 8 icon="trash" 9 onPress={() => { 10 params.navigateToTrash(); 11 }} 12 /> 13 ), 14 // previous header config here... 15 }; 16 };
Next, update the state initialization code to include a default value for removed_pokemon
:
1state = { 2 pokemon: updated_pokemon, 3 removed_pokemon: [], // add this 4 isDropAreaVisible: false 5 };
After that, we set the navigateToTrash
function as a navigation param:
1constructor(props) { 2 /* previously added constructor code here */ 3 4 this.props.navigation.setParams({ 5 navigateToTrash: this.navigateToTrash 6 }); 7 }
Here’s the navigateToTrash
method. We can’t really use this screen’s state from inside the navigationOptions
, that’s why we’re setting this function as a navigation param:
1navigateToTrash = () => { 2 this.props.navigation.navigate("Trash", { 3 removed_pokemon: this.state.removed_pokemon 4 }); 5 };
Next, update the removePokemon
method to include manipulation of removed_pokemon
:
1removePokemon = item => { 2 let pokemon_data = [...this.state.pokemon]; 3 let removed_pokemon_data = [...this.state.removed_pokemon]; // add this 4 let index = pokemon_data.findIndex(itm => itm.name == item.name); 5 let removed_pokemon = pokemon_data.splice(index, 1); // add 'let removed_pokemon' to this line 6 removed_pokemon_data.push(removed_pokemon[0]); // add this 7 LayoutAnimation.configureNext(animationConfig); 8 9 this.setState({ 10 pokemon: pokemon_data, 11 removed_pokemon: removed_pokemon_data // add this 12 }); 13 };
Lastly, update the Root.js
file to include the Trash screen as one of the screens of the app:
1import TrashScreen from "./src/screens/Trash"; 2 3 const transitionConfig = () => { 4 // previous transition config here... 5 }; 6 7 const MainStack = createStackNavigator( 8 { 9 // previous screens here.. 10 Trash: { 11 screen: TrashScreen 12 } 13 }, 14 // previous config 15 );
Once that’s done, you should be able to test the swiping gesture.
The final gesture that we’re going to implement is pinch gesture, and it looks like this:
In the above demo, the user uses a pinch gesture to zoom the image in and out. In my opinion, this gesture is one of the most complex ones that you can implement. So instead of implementing it with the PanResponder, we’ll use the React Native Gesture Handler library to make it easier.
Before we proceed, let’s take a look at the work involved in implementing this:
PinchableImage
component. This is where we will use the gesture handler library to implement a pinch-to-zoom gesture.BigCard
component to replace the original image with the PinchableImage
component.You can install the gesture handler with the following command:
1npm install --save react-native-gesture-handler
At the time of writing this tutorial, react-native link
doesn’t really link the native modules to the project. So we’ll have to use Cocoapods instead. This also means that you’ll have to do the manual install for Android if you’re planning to test on both iOS and Android.
If you only need to test on Android, you should be able to get away with using react-native link
to link the native module. We’ll get to the Android installation shortly, first let’s get into iOS.
cd
into the ios
directory and initialize a new Podfile
:
1cd ios 2 pod init
Next, replace its contents with the following. Here we’re adding React Native modules as pods, then below it (pod 'RNGestureHandler``'
) is where we include the actual module for the gesture handler:
1target 'RNRealworldAnimations' do 2 3 rn_path = '../node_modules/react-native' 4 pod 'yoga', path: "#{rn_path}/ReactCommon/yoga/yoga.podspec" 5 pod 'React', path: rn_path, subspecs: [ 6 'Core', 7 'CxxBridge', 8 'DevSupport', 9 'RCTActionSheet', 10 'RCTAnimation', 11 'RCTGeolocation', 12 'RCTImage', 13 'RCTLinkingIOS', 14 'RCTNetwork', 15 'RCTSettings', 16 'RCTText', 17 'RCTVibration', 18 'RCTWebSocket', 19 ] 20 21 pod 'DoubleConversion', :podspec => "#{rn_path}/third-party-podspecs/DoubleConversion.podspec" 22 pod 'glog', :podspec => "#{rn_path}/third-party-podspecs/glog.podspec" 23 pod 'Folly', :podspec => "#{rn_path}/third-party-podspecs/Folly.podspec" 24 25 pod 'RNGestureHandler', :path => '../node_modules/react-native-gesture-handler/ios' 26 end 27 28 post_install do |installer| 29 installer.pods_project.targets.each do |target| 30 if target.name == "React" 31 target.remove_from_project 32 end 33 end 34 end
After that, install all the pods:
1pod install
Once that’s done, you can now run your project:
1cd .. 2 react-native run-ios
To configure it on Android, open the android/settings.gradle
file and add the following right before the include ':app``'
:
1include ':react-native-gesture-handler' 2 project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android')
Next, open android/app/build.gradle
and include react-native-gesture-handler
right after react-native-vector-icons
:
1dependencies { 2 compile project(':react-native-vector-icons') 3 compile project(':react-native-gesture-handler') 4 // ...other dependencies here 5 }
Next, open android/app/src/main/java/com/rnrealworldanimations/MainApplication.java
and import the corresponding gesture handler library:
1// other previously imported libraries here 2 import com.facebook.soloader.SoLoader; // previously imported library 3 import com.swmansion.gesturehandler.react.RNGestureHandlerPackage; // add this
Then use it inside getPackages
:
1protected List<ReactPackage> getPackages() { 2 return Arrays.<ReactPackage>asList( 3 new MainReactPackage(), 4 new VectorIconsPackage(), 5 new RNGestureHandlerPackage() // add this 6 ); 7 }
Lastly, open android/app/src/main/java/com/rnrealworldanimations/MainActivity.java
and import the gesture handler libraries:
1package com.rnrealworldanimations; 2 3 import com.facebook.react.ReactActivity; 4 import com.facebook.react.ReactActivityDelegate; // add this 5 import com.facebook.react.ReactRootView; // add this 6 import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView; // add this
Inside the class, use ReactActivityDelegate
to enable the gesture handler on the root view:
1public class MainActivity extends ReactActivity { 2 3 @Override 4 protected String getMainComponentName() { 5 return "RNRealworldAnimations"; 6 } 7 8 // add everything below this line 9 @Override 10 protected ReactActivityDelegate createReactActivityDelegate() { 11 return new ReactActivityDelegate(this, getMainComponentName()) { 12 @Override 13 protected ReactRootView createRootView() { 14 return new RNGestureHandlerEnabledRootView(MainActivity.this); 15 } 16 }; 17 } 18 }
Once that’s done, execute react-native run-android
from your terminal to rebuild and run the project.
Create a src/components/PinchableImage.js
file and add the following. React Native Gesture Handler is only responsible for handling the gesture, you still have to write the code for the animations to be applied when those gestures are performed by the user. That’s why we still need to include the Animated
module:
1import React, { Component } from "react"; 2 import { Animated, View, Dimensions } from "react-native"; 3 import { PinchGestureHandler, State } from "react-native-gesture-handler"; 4 5 const { width, height } = Dimensions.get("window"); // used for dealing with image dimensions 6 7 export default class PinchableImage extends Component { 8 9 // next: add constructor 10 11 }
Most of the time, all you will need to extract from the gesture handler module is the gesture you want to handle, and the State
. In this case, we want to use the PinchGestureHandler
. But you can also use handlers like FlingGestureHandler
to implement the swiping gesture that we did earlier, or the PanGestureHandler
to implement a drag-and-drop. Best of all, you can combine these gesture handlers together to create more complex interactions.
Next, in the constructor
, we initialize the animated values that we will be using:
baseScale
– the default scale value of the image. Here, we’ve set it to 1
so that if it becomes larger than 1
then the user is making the image larger. If it’s less than 1
then the user is making it smaller.pinchScale
– the scale value for the pinch gesture.scale
– the actual scale value to be used for the transform scale.lastScale
– the scale value to be used for updating the baseScale
.imageScale
– the current scale value of the image.Here’s the code:
1// src/components/PinchableImage.js 2 constructor(props) { 3 super(props); 4 this.baseScale = new Animated.Value(1); 5 this.pinchScale = new Animated.Value(1); 6 this.scale = Animated.multiply(this.baseScale, this.pinchScale); 7 this.lastScale = 1; 8 this.imageScale = 0; 9 }
Throughout the lifecycle of the whole gesture, the _onPinchHandlerStateChange
method will be executed. Previously, we’ve used onPanResponderGrant
, onPanResponderMove
and onPanResponderRelease
. But when using the gesture handler, it’s consolidated into a single method. Though this time, there’s the handler state which is used to respond to different states of the gesture. Here’s how it maps to the PanResponder methods:
onPanResponderGrant
– State.BEGAN
onPanResponderMove
– State.ACTIVE
onPanResponderRelease
– State.END
Additionally, there’s also State.UNDETERMINED
, State.CANCELLED
, and State.FAILED
.
Since we don’t really need to perform anything when the gesture is started or ended, we wrap everything in State.ACTIVE
condition. Inside it, we calculate the newImageScale
. We do that by first determining whether the user’s fingers have traveled away from each other or near each other. If event.nativeEvent.scale
is negative, then it means the user is trying to zoom it out. Otherwise (larger than 0
) the user is zooming it in. We then use it to determine whether to add or subtract the currentScale
from the imageScale
. Here’s the code:
1// src/components/PinchableImage.js 2 _onPinchHandlerStateChange = event => { 3 if (event.nativeEvent.oldState === State.ACTIVE) { 4 let currentScale = event.nativeEvent.scale; // the distance travelled by the user's two fingers 5 6 this.lastScale *= event.nativeEvent.scale; // the value we will animated the baseScale to 7 this.pinchScale.setValue(1); // everytime the handler is triggered, it's considered as 1 scale value 8 9 // the image's new scale value 10 let newImageScale = 11 currentScale > 0 12 ? this.imageScale + currentScale 13 : this.imageScale - currentScale; 14 15 // next: add code for checking if scale is within range 16 17 } 18 };
Next, we determine if the newImageScale
is within range. If it is, then we use a spring animation to scale the image:
1if (this.isScaleWithinRange(newImageScale)) { 2 Animated.spring(this.baseScale, { 3 toValue: this.lastScale, 4 bounciness: 20, 5 useNativeDriver: true 6 }).start(); 7 this.imageScale = newImageScale; // don't forget to update the imageScale 8 } else { 9 // next: add code for animating the component if it's not within range 10 }
If it’s not within range, then we scale the image back to its original size:
1this.lastScale = 1; 2 this.imageScale = 0; 3 Animated.spring(this.baseScale, { 4 toValue: 1, 5 bounciness: 20, 6 useNativeDriver: true 7 }).start();
The isScaleWithinRange
function is used to determine whether the scale is still within a specific limit. In this case, we don’t want the image to become smaller than half its size (0.5
), and we also don’t want it to become five times (5
) larger than its original size:
1// src/components/PinchableImage.js 2 isScaleWithinRange = newImageScale => { 3 if (newImageScale >= 0.5 && newImageScale <= 5) { 4 return true; 5 } 6 return false; 7 };
In order for the component to respond to pinch gesture, we wrap everything inside the PinchGestureHandler
component. This handler only requires you to pass the onHandlerStateChange
prop which gets executed throughout the lifecycle of the gesture. Inside it are the components you want to animate as the gesture is being performed by the user. Here’s the render
method:
1render() { 2 return ( 3 <PinchGestureHandler 4 onHandlerStateChange={this._onPinchHandlerStateChange} 5 > 6 <View style={styles.container}> 7 <View style={styles.imageContainer}> 8 <Animated.Image 9 resizeMode={"contain"} 10 source={this.props.image} 11 style={[ 12 styles.pinchableImage, 13 { 14 transform: [{ scale: this.scale }] 15 } 16 ]} 17 /> 18 </View> 19 </View> 20 </PinchGestureHandler> 21 ); 22 }
You can also combine multiple gestures by wrapping the components inside multiple gesture handlers.
Next, add the styles:
1const styles = { 2 container: { 3 flex: 1 4 }, 5 imageContainer: { 6 width: width, 7 overflow: "visible", 8 alignItems: "center" 9 }, 10 pinchableImage: { 11 width: 250, 12 height: height / 2 - 100 13 } 14 };
Next, we update the BigCard
component to use the PinchableImage
in place of the Animated.Image
that we currently have:
1// src/components/BigCard.js 2 import PinchableImage from "./PinchableImage";
Inside the component, we update the final output range of titleMoveY
to be equal to half of the screen’s size:
1import { /*previously imported modules*/ Dimensions } from "react-native"; 2 const { height } = Dimensions.get("window"); 3 4 export default class BigCard extends Component<Props> { 5 const titleMoveY = this.titleTranslateYValue.interpolate({ 6 inputRange: [0, 1], 7 outputRange: [0, height / 2] 8 }); 9 }
All the other animated values (titleScale
stays the same). Note that we’ve also removed the animated value for the image opacity. This means that image will no longer be animated when the user views the Details screen. The only animation it’s going to perform is when the user uses the pinch gesture.
Next, replace Animated.Image
with PinchableImage
:
1return ( 2 <View style={styles.container}> 3 <View style={styles.imageContainer}> 4 <View style={styles.mainContainer}> 5 <PinchableImage image={image} /> 6 ... 7 </View> 8 </View> 9 </View> 10 );
Once that’s done, you should be able to use a pinch gesture on the image to make it larger or smaller.
In this tutorial, you’ve learned how to implement drag-and-drop, swiping, and pinch gestures. You’ve also learned how implementing gesture animations can be quite code-heavy. Good thing there are libraries like the React Native Gesture Handler which makes it easy to respond to user gestures.
The full source code for this tutorial is available on this GitHub repo. Be sure to switch to the part3
branch if you want the final output for this part of the series.