0
0
React Nativemobile~5 mins

Animated API basics in React Native

Choose your learning style9 modes available
Introduction

The Animated API helps you create smooth and interactive animations in your app. It makes your app feel alive and fun to use.

When you want a button to smoothly change size when pressed.
When you want to fade in a picture or text on the screen.
When you want to move an object across the screen smoothly.
When you want to create a loading spinner animation.
When you want to animate a list item sliding in or out.
Syntax
React Native
import { Animated } from 'react-native';

const value = new Animated.Value(0);

Animated.timing(value, {
  toValue: 1,
  duration: 500,
  useNativeDriver: true,
}).start();

Animated.Value holds the animation value that changes over time.

Animated.timing changes the value smoothly from a start to an end value.

Examples
This example fades in an element by animating its opacity from 0 to 1 in 1 second.
React Native
const opacity = new Animated.Value(0);

Animated.timing(opacity, {
  toValue: 1,
  duration: 1000,
  useNativeDriver: true,
}).start();
This example moves an element horizontally by animating its position value from 0 to 100.
React Native
const position = new Animated.Value(0);

Animated.timing(position, {
  toValue: 100,
  duration: 500,
  useNativeDriver: true,
}).start();
Sample App

This app shows a blue box that starts invisible. When you press the "Fade In" button, the box smoothly appears by increasing its opacity from 0 to 1 over 1 second.

React Native
import React, { useRef } from 'react';
import { Animated, View, Button, StyleSheet } from 'react-native';

export default function AnimatedBox() {
  const fadeAnim = useRef(new Animated.Value(0)).current;

  const fadeIn = () => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
    }).start();
  };

  return (
    <View style={styles.container}>
      <Animated.View
        style={[styles.box, { opacity: fadeAnim }]} />
      <Button title="Fade In" onPress={fadeIn} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  box: {
    width: 100,
    height: 100,
    backgroundColor: 'blue',
    marginBottom: 20,
  },
});
OutputSuccess
Important Notes

Always set useNativeDriver: true for better performance when animating properties like opacity or position.

You can animate many properties like opacity, position, scale, and rotation using Animated API.

Remember to use Animated.View or other Animated components to apply animations.

Summary

The Animated API lets you create smooth animations easily.

Use Animated.Value to hold animation values.

Use Animated.timing to change values over time with smooth transitions.