TutorialsCourses
Course Menu
React Native Animated for Beginners

Rotate Square

Basic Rotation

import React from "react";
import { StyleSheet, Text, View, Animated } from "react-native";

const SampleApp = React.createClass({
  componentWillMount: function () {
    this._animatedValue = new Animated.Value(0);
  },
  componentDidMount: function () {
    Animated.timing(this._animatedValue, {
      toValue: 100,
      duration: 3000,
    }).start();
  },
  render: function () {
    const interpolatedRotateAnimation = this._animatedValue.interpolate({
      inputRange: [0, 100],
      outputRange: ["0deg", "360deg"],
    });

    return (
      <View style={styles.container}>
        <Animated.View
          style={[
            styles.box,
            { transform: [{ rotate: interpolatedRotateAnimation }] },
          ]}
        />
      </View>
    );
  },
});

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  box: {
    backgroundColor: "red",
    position: "absolute",
    top: 100,
    left: 100,
    width: 100,
    height: 100,
  },
});

Merge them all together

We just need to adjust our render function to bring all the code together

const interpolatedRotateAnimation = this._animatedValue.interpolate({
  inputRange: [0, 100],
  outputRange: ["0deg", "360deg"],
});

const interpolatedColorAnimation = this._animatedValue.interpolate({
  inputRange: [0, 100],
  outputRange: ["rgba(255,255,255, 1)", "rgba(51,156,177, 1)"],
});

return (
  <View style={styles.container}>
    <Animated.View
      style={[
        styles.box,
        {
          backgroundColor: interpolatedColorAnimation,
          transform: [
            { translateY: this._animatedValue },
            { rotate: interpolatedRotateAnimation },
          ],
        },
      ]}
    />
  </View>
);