How to Create Spring Animation in React Native

This is the fourth part of the react native animation tutorial series. I have already posted about fading animations, scaling animations, and moving animations. In this blog post, let’s discuss how to add a spring animation effect in react native.

By spring animation what I mean is an animating movement that follows spring animation. In earlier posts, we used Animated.timing() method but here you need to use Animated.spring() method to attain the desired effect.

In this react native spring animation example, we change the scale/size of a square with a spring effect. As usual, you have to declare initial values.

const startValue = useRef(new Animated.Value(1)).current;
const endValue = 1.5;

Then we use Animated.spring() to start the animation. It accepts many configurations such as stiffness, friction, tension, speed, etc.

Animated.spring(startValue, {
      toValue: endValue,
      friction: 1,
      useNativeDriver: true,
    }).start();

As we are changing the size of the square, we should use Animated.View and transform prop.

<Animated.View
        style={[
          styles.square,
          {
            transform: [
              {
                scale: startValue,
              },
            ],
          },
        ]}
      />

Here’s the full example of react native spring animation.

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

const Spring = () => {
  const startValue = useRef(new Animated.Value(1)).current;
  const endValue = 1.5;

  useEffect(() => {
    Animated.spring(startValue, {
      toValue: endValue,
      friction: 1,
      useNativeDriver: true,
    }).start();
  }, [startValue]);

  return (
    <View style={styles.container}>
      <Animated.View
        style={[
          styles.square,
          {
            transform: [
              {
                scale: startValue,
              },
            ],
          },
        ]}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  square: {
    height: 50,
    width: 50,
    backgroundColor: 'red',
  },
});

export default Spring;

Following is the output of the example:

spring animation example react native

You can get the source code of all my animation examples given in this tutorial series from this Github repository.

1 thought on “How to Create Spring Animation in React Native”

Leave a Reply

%d bloggers like this: