Membuat UI Animasi di React Native

Dipublikasikan: 12 Januari 2025 • Kategori: Developer • Penulis: Jumanto

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

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.

← Kembali ke Blog