Table of contents
1.
Introduction
2.
Animated API
2.1.
Configuring Animation
2.2.
Working with Animations
2.3.
Composing Animation
2.4.
Combining Animated Values
2.5.
Interpolation
2.6.
Handling gestures and other events
2.7.
Example
3.
LayoutAnimation
3.1.
Example
4.
Frequently Asked Questions
4.1.
What is React Native Animation?
4.2.
What is the difference between Animated and LayoutAnimation?
4.3.
What are different animatable components in react native?
4.4.
How do you loop animation in React Native?
4.5.
What is interpolation in React Native?
5.
Conclusion
Last Updated: Mar 27, 2024

React Native Animations

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Animations enable you to depict physically believable motion in your interface. Animations are critical for a great user experience.

React Native has two animation systems: Animated and LayoutAnimation. Animated allows for detailed and interactive modification of particular values, while LayoutAnimation allows for animated global layout transactions.


Click on the following link to read further: Hooks in React JS

Animated API

The Animated API represents a wide range of fascinating animation and interaction patterns in a clear and performant manner. Animated emphasizes direct relationships between inputs and outputs and adjustable transforms and start/stop methods for controlling time-based animation execution.

Animated exports six types of animatable components:

  • View
  • Text
  • Image
  • ScrollView
  • FlatList
  • SectionList

However, you can also make your own using Animated.createAnimatedComponent().

Configuring Animation

There are three types of animation available in Animated. Each animation type has its animation curve that determines how your values animate from their initial value to their final value:

  • Animated. timing(): The value is animated along a timed easing curve.
  • Animated. spring(): Animates following the analytical spring model based on damped harmonic oscillation.
  • Animated.decay(): Based on a decay coefficient, it animates a value from an initial velocity to zero.

Working with Animations

The following steps can be taken to implement animations in React Native:

  • Import the animation modules.
  • Declare an animated value.
  • Define how the animated value changes over time.
  • Set the animated style for the component and render an animated version of it.
  • Start the animation.

Start animations by executing start() on your animation. start() accepts a completion callback that will be triggered when the animation is finished. If the animation is typically completed, then the completion callback will be called with the parameter {finished: true}. If stop() were called on the animation before it could finish (for example, because a gesture or another animation halted it), it would receive {finished: false}.

Animated.timing({}).start(({ finished }) => {
  /* completion callback */
});

Composing Animation

Composition functions can be used to combine animations in complex ways:

  • Animated.delay() : animation starts after a given delay.
  • Animated. parallel(): number of animations start at the same time.
  • Animated. sequence(): starts the animations one by one, waiting for each one to finish before moving on to the next.
  • Animated. stagger(): this starts animations in order and parallel, but with a delay between them.
Animated.sequence([
  // decay, then spring to start and twirl
  Animated.decay(position, {
    velocity: { x: gestureState.vx, y: gestureState.vy }, // velocity from gesture release
    deceleration: 0.997
  }),
  Animated.parallel([
    // after decay, in parallel:
    Animated.spring(position, {
      toValue: { x: 0, y: 0 } // return to start
    }),
    Animated.timing(twirl, {
      // and twirl
      toValue: 360
    })
  ])
]).start(); // starting the sequence group

Combining Animated Values

You can make a new animated value by adding, subtracting, multiplying, dividing, or moduloing two animated values:

  • Animated.add()
  • Animated.subtract()
  • Animated.divide()
  • Animated.modulo()
  • Animated.multiply()
//An example, inverting a scale (2x --> 0.5x)
const a = new Animated.Value(1);
const b = Animated.divide(1, a);
Animated.spring(a, {
  toValue: 2
}).start();

Interpolation

The interpolate() method lets you map different input ranges to different output ranges. By default, it will extrapolate the curve beyond the supplied fields, but you may also clamp the output value. By default, it employs linear interpolation but also allows easing functions.

//to convert a 0-1 range to a 0-100 range
value.interpolate({
  inputRange: [0, 1],
  outputRange: [0, 100]
});

Also see,  React Native Reanimated

Handling gestures and other events

Animated. event() can map gestures like panning and scrolling, as well as other events, to animated values. This is accomplished by using a structured map syntax, which allows values to be extracted from complex event objects.

Example

The view in the following example will fade in and out based on the animated variable animFade. The opacity of the view will change to 1 in 5 seconds and back to 0 in 1 second on clicking the "Fade in View" and "Fade out View" buttons, respectively.

import React, { Component } from "react";
import { Animated, Text, View, StyleSheet, Button, SafeAreaView } from "react-native";
class App extends Component {
  // animFade will be used as the value for opacity. Initial Value: 0
  state = {
    animFade: new Animated.Value(0)
  };
  fadeIn = () => {
    Animated.timing(this.state.fadeAnim, {
      toValue: 1,
      duration: 5000
    }).start();
  };
  fadeOut = () => {
      Animated.timing(this.state.fadeAnim, {
      toValue: 0,
      duration: 1000
    }).start();
  };
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <Animated.View
          style={[
            styles.fadingContainer,
            {
              // Bind opacity to animated value
              opacity: this.state.animFade
            }
          ]}
        >
          <Text style={styles.fadingText}>Fading View!</Text>
        </Animated.View>
        <View style={styles.buttonRow}>
          <Button title="Fade In View" onPress={this.fadeIn} />
          <Button title="Fade Out View" onPress={this.fadeOut} />
        </View>
      </SafeAreaView>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  fadingContainer: {
    padding: 20,
    backgroundColor: "powderblue"
  },
  fadingText: {
    fontSize: 28
  },
  buttonRow: {
    flexBasis: 100,
    justifyContent: "space-evenly",
    marginVertical: 16
  }
});
export default App;

LayoutAnimation

LayoutAnimation allows you to generate and change animations for all views in the next render/layout cycle from a single location. This is useful for updating Flexbox layouts without having to measure or calculate specific properties to animate them directly, and it's advantageous when layout changes may affect ancestors.

Note: Although LayoutAnimation is extremely strong and helpful, it offers significantly less control than Animated and other animation libraries.

To make this work on Android, you'll need to use UIManager to set the necessary flags:

if (Platform.OS === 'android') {
  if (UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }
}

Example

We develop a TouchableOpacity and a View component in this example. When we press the TouchableOpacity component, it invokes the _onPress() method, which animates the View component by increasing its width and height by 15 units.

import React from 'react';
import {
  NativeModules,
  LayoutAnimation,
  Text,
  TouchableOpacity,
  StyleSheet,
  View,
} from 'react-native';
const { UIManager } = NativeModules;
UIManager.setLayoutAnimationEnabledExperimental &&
  UIManager.setLayoutAnimationEnabledExperimental(true);
export default class App extends React.Component {
  state = {
    w: 100,
    h: 100,
  };
  _onPress = () => {
    // Animate the update
    LayoutAnimation.spring();
    this.setState({w: this.state.w + 15, h: this.state.h + 15})
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={[styles.box, {width: this.state.w, height: this.state.h}]} />
        <TouchableOpacity onPress={this._onPress}>
          <View style={styles.button}>
            <Text style={styles.buttonText}>Press me!</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  box: {
    width: 200,
    height: 200,
    backgroundColor: 'red',
  },
  button: {
    backgroundColor: 'black',
    paddingHorizontal: 20,
    paddingVertical: 15,
    marginTop: 15,
  },
  buttonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
});

Frequently Asked Questions

What is React Native Animation?

Animations enable you to depict physically believable motion in your interface. Animations are critical for a great user experience. React Native has two animation systems: Animated and LayoutAnimation.

What is the difference between Animated and LayoutAnimation?

Animated allows for detailed and interactive modification of particular values, while LayoutAnimation allows for animated global layout transactions.

What are different animatable components in react native?

View, Text, Image, ScrollView, FlatList, and SectionList are the six animatable components, Animated API exports. However, you can also make your own using Animated.createAnimatedComponent().

How do you loop animation in React Native?

In react Native, we should employ the Animated. loop() method to create looping animations. Wrap your animations with Animated. loop(), and they'll play back in a loop.

What is interpolation in React Native?

The interpolate() method lets you map different input ranges to different output ranges. It will extrapolate the curve beyond the supplied ranges by default, but you may also clamp the output value. By default, it employs linear interpolation.

Conclusion

In this article, we have discussed React Native Animation and learned how to implement it in an app. We have discussed two complementary animation systems of React Native in detail.

After learning how to infuse animation in your application using React Native, are you curious to know more about app development using React Native? We have you covered. Check out MobileMobile TechnologiesHow To Make A Mobile App In 9 Easy Steps, and guided path on Fundamentals of React Native.

Refer to guided paths on Coding Ninjas Studio to upskill yourself in Data Structure and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more. If you want to test your competency in coding, you may check out the mock test series and participate in a contest hosted by Coding Ninjas Studio! But suppose you have just started the learning process and looking for the question asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Live masterclass