I have an issue in the animation of the circle. The flow is: When user will click on button 1, the circle will animate from real position to position 1,
When clicking button2, a circle will move from position 1 to position 2,
and
When clicking on button2, a circle will animate back on the real position.
I need 1 sec. time while animate and I want to set circle position at particular Y position. mean the first position on Y=400, second position on Y= 100.
Thanks in advance
You need to use the Animated library from react-native. Check out the library for more details on how to animate objects.
Meanwhile check the working example in Snack.io
Here's the code.
import React, { Component } from "react";
import { View, Text, StyleSheet, Animated, TouchableOpacity } from "react-native";
export default class App extends Component {
constructor() {
super();
this.state = {
posY: new Animated.Value(400)
};
}
moveBall = (yPos) => {
Animated.timing(this.state.posY, {
toValue: yPos,
duration: 1000
}).start()
};
renderRectangle = () => {
const animatedStyle = { top: this.state.posY };
return (
<Animated.View style={[styles.rectangle, animatedStyle]}>
</Animated.View>
);
};
render() {
return (
<View style={styles.container}>
<View style={{ flex: 0.9, alignItems: 'center' }}>
{this.renderRectangle()}
</View>
<View style={styles.buttonsContainer}>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => this.moveBall(250)}
>
<Text>Button 1</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => this.moveBall(100)}
>
<Text>Button 2</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => this.moveBall(400)}
>
<Text>Button 3</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
rectangle: {
backgroundColor: "#2c3e50",
width: 50,
height: 50,
borderRadius: 50,
position: 'absolute'
},
buttonsContainer: {
flex: 0.1,
flexDirection: 'row',
justifyContent: 'space-between',
paddingLeft: 20,
paddingRight: 20
},
buttonStyle: {
padding: 5,
height: 30,
backgroundColor: 'limegreen'
}
});