How to move a View from/ to positions?
Points
- Where is the item right now? X, Y position on the screen?
- Animated.Value
- Animated.ValueXY
- Where is the item moving to? What’s the end goal of the item (position, color, shape…)
- Animated.Types.Spring
- Animated.Types.Decay
- Animated.Types.Timing
- Which element are we moving?
- Animated.Components.View
- Animated.Components.Text
- Animated.Components.Image
How to display a message moving from top to down?
Create message View
import React from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
const AnimatedMsg = () => {
return (
<View style={styles.notification}>
<Text style={styles.notificationText}>Test notification</Text>
</View>
);
};
export default AnimatedMsg;
const styles = StyleSheet.create({
notification: {
position: 'absolute',
paddingHorizontal: 7,
paddingVertical: 15,
left: 0,
top: -100,
right: 0,
backgroundColor: 'tomato',
},
notificationText: {
color: '#FFF',
}
});
3 required values
- Where is the item?
Animated.ValueXY - Where is the element moving to?
Animated.Spring - Which element are we moving?
Animated.View
...
import {
Animated,
...
} from 'react-native';
const AnimatedMsg = () => {
const position = new Animated.ValueXY({ x: 0, y: 0 });
Animated.spring(position, {
toValue: { x: 0, y: 100 },
useNativeDriver: false,
}).start();
return (
<Animated.View style={position.getLayout()}>
...
</Animated.View>
);
};
...
Create a button to trigger the moving animation
...
const AnimatedMsg = () => {
const position = new Animated.ValueXY({ x: 0, y: 0 });
const handlePress = () => {
Animated.spring(position, {
toValue: { x: 0, y: 200 },
useNativeDriver: false,
}).start();
}
return <>
<Animated.View style={position.getLayout()}>
...
</Animated.View>
<TouchableOpacity onPress={this.handlePress}>
<View style={styles.button}>
<Text style={styles.buttonText}>Show Notification</Text>
</View>
</TouchableOpacity>
</>;
};
...
Move a message back to the original position
...
const handlePress = () => {
Animated.sequence([
Animated.spring(position, {
toValue: { x: 0, y: 100 },
useNativeDriver: false,
}),
Animated.delay(1500),
Animated.spring(position, {
toValue: { x: 0, y: -100 },
useNativeDriver: false,
}),
]).start();
};
...
Leave a Reply