Animasi adalah elemen penting dalam aplikasi modern. UI terasa lebih halus, natural, dan memberikan pengalaman pengguna yang jauh lebih baik. Di React Native, dua library animasi yang paling kuat adalah Reanimated 2 dan Gesture Handler.
1. Instalasi Reanimated dan Gesture Handler
Install library berikut:
npm install react-native-reanimated react-native-gesture-handler
Tambahkan juga konfigurasi Reanimated di bawah ini:
// babel.config.js
module.exports = {
presets: ["module:metro-react-native-babel-preset"],
plugins: ["react-native-reanimated/plugin"],
};
2. Membuat Animasi Fade In
Contoh animasi sederhana menggunakan Reanimated 2:
import Animated, { useSharedValue, useAnimatedStyle, withTiming } from "react-native-reanimated";
export default function FadeInBox() {
const opacity = useSharedValue(0);
const style = useAnimatedStyle(() => ({
opacity: opacity.value
}));
useEffect(() => {
opacity.value = withTiming(1, { duration: 800 });
}, []);
return (
<Animated.View style={[{ width: 100, height: 100, backgroundColor: "skyblue" }, style]} />
);
}
3. Animasi Geser (Slide Animation)
const offset = useSharedValue(-200);
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ translateX: offset.value }]
}));
useEffect(() => {
offset.value = withTiming(0, { duration: 600 });
}, []);
Gunakan untuk membuat sidebar, overlay, atau pop-up.
4. Interaksi Gesture Handler (Drag Box)
Gesture Handler digunakan untuk membuat elemen dapat digeser (drag).
import { PanGestureHandler } from "react-native-gesture-handler";
import Animated, { useSharedValue, useAnimatedGestureHandler, useAnimatedStyle } from "react-native-reanimated";
export default function DragBox() {
const x = useSharedValue(0);
const y = useSharedValue(0);
const gesture = useAnimatedGestureHandler({
onActive: (event) => {
x.value = event.translationX;
y.value = event.translationY;
}
});
const style = useAnimatedStyle(() => ({
transform: [
{ translateX: x.value },
{ translateY: y.value }
]
}));
return (
<PanGestureHandler onGestureEvent={gesture}>
<Animated.View style={[{ width: 100, height: 100, backgroundColor: "orange" }, style]} />
</PanGestureHandler>
);
}
5. Best Practice Animasi React Native
- Gunakan Reanimated 2 untuk performa terbaik.
- Hindari animasi berat di screen dengan banyak komponen.
- Gunakan gesture handler untuk interaksi seperti drag & swipe.
- Gunakan withSpring() untuk animasi natural.
- Letakkan animasi di komponen terpisah agar kode tetap rapi.
6. Contoh Kombinasi Spring Animation
offset.value = withSpring(0, {
damping: 12,
stiffness: 120
});
Dengan Reanimated dan Gesture Handler, kamu bisa membuat animasi yang halus, natural, dan berkualitas profesional pada aplikasi React Native.