React native animated bounce is quite easy and in this tutorial, you will learn how to use the spring animation function to create a bounce object with animation.
Animated.spring uses friction and tension to stimulate real world fall object.
The default values for friction and tension are 7 and 40.
Friction tells how quickly the animation should come down. The higher the value the faster it calms down. And Tension tells the animation how much energy it should have.
For the ball object, we used absolute positioning. Since we are absolute positioning in react starts from upper left corner, we initialized the top value to 150 in our state variable which is an Animated.Value(150)
state={
animation: new Animated.Value(150)
}
We start the bounce animation once we click on the handlePress() function which is invoked from the TouchableOpacity.
Wihtin TouchableOpacity, we used Animated.Spring API, which takes a few values. Apart from toValue and duration, we added two extra property.
We used friction as 1 and tension 20
import React, { Component } from 'react';
import {View, StyleSheet, TouchableOpacity, Animated} from 'react-native';
export default class Bounce extends Component {
state={
animation: new Animated.Value(150)
}
handlePress=()=>{
Animated.spring(this.state.animation,{
toValue:450,
duration:2000,
friction:1,
tension:20,
useNativeDriver:true
}).start();
}
render(){
const trans={
transform:[
{translateY:this.state.animation}
]
}
return (
<>
<Animated.View style={[styles.ball, trans]}>
</Animated.View>
<View style={styles.container}>
<TouchableOpacity onPress={this.handlePress} style={styles.button}>
</TouchableOpacity>
</View>
</>
);
}
}
const styles=StyleSheet.create({
ball:{
width:100,
height:100,
borderRadius:50,
backgroundColor:"tomato",
position:"absolute",
left:160,
//top:150,
},
button:{
width:150,
height:70,
padding:10,
borderRadius:10,
backgroundColor:"#fc5c65",
marginVertical:50,
},
container:{
flex:1,
justifyContent:"flex-end",
alignItems:"center",
},
});
But if you want more realistic animation you can skip the duration value and play with it.
Build a complete e-commerce app with backend
Build a complete backend with Laravel
Build a mobile app with Flutter and Laravel