import React, { useRef, useState } from 'react';
import { View, Button, Animated, StyleSheet } from 'react-native';
export default function AnimationDemo() {
const animation = useRef(new Animated.Value(0)).current;
const [moved, setMoved] = useState(false);
const moveBox = () => {
Animated.timing(animation, {
toValue: moved ? 0 : 200,
duration: 1000,
useNativeDriver: true
}).start(() => {
setMoved(!moved);
});
};
return (
<View style={styles.container}>
<Animated.View style={[styles.box, { transform: [{ translateX: animation }] }]} />
<Button title="Move Box" onPress={moveBox} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-between',
alignItems: 'flex-start',
padding: 20
},
box: {
width: 50,
height: 50,
backgroundColor: 'blue'
}
});This example uses React Native's Animated API to create a smooth movement of a blue box across the screen. The animation value controls the horizontal position of the box.
When the user taps the 'Move Box' button, the moveBox function triggers an animation that moves the box from its current position to the other side (0 to 200 pixels or back). The Animated.timing function smoothly changes the position over 1 second.
This smooth transition feels natural and fluid, unlike an instant jump. Animations like this help users understand changes on screen and make the app feel polished and responsive.