Animated API

Basic Animation in React Native using Animated API

Animation in react native using animated API are an important part of the UX of an application. However, animations will significantly impact a user for a better interaction experience, and it smoothens user engagement. Also, there is the extended functionality to perform; animation is the most useful idea to engage users.

Animations have the moment from a static state to a motion state for better user interaction. It also has multiple transitions to show elements, making it amazing.

You might be thinking of integrating React Native Animations by utilising Animated API and searching for how to beg. Then, here is the complete guide on adding React Native animations from scratch till the end.

Types of React Native Animation

Let’s discuss the following React Native Animation Types below.

1. Animated.timing()

Allows us to define specific values over a specific amount of time.

2. Animated.spring()

Define animations from beginning points to finish points without defining time as we did in timings.

3. Animated.parallel()

Describing animations in an array to trigger at a similar time.

4. Animated.sequence()

It allows us to use all the pre-defined animations in the array to trigger one after another.

React Native Animated API

React Native provides an Animated library which helps us to do various animation effects in our application. It is very easy to use and implement in our code. So, in this blog we will see the basic concepts, implementations and methods of Animated library.

Firstly we require to import the Animated module from react-native

	
       import {Animated } from 'react-native';

Now we need to set the initial Animated value. For that, we can use the useRef hook from React.

	
        const animatedValue = useRef(new Animated.Value(0)).current;

Now we need to set the initial Animated value. For that, we can use the useRef hook from React.

So we have set our initial value to 0.

Now let’s see an example to understand this; suppose there is a text, and you must move it horizontally, like oscillating to the right and left at a particular interval. We can do that now. You need to position the text in the centre first.

In style, there is a transform property. This provides another two properties that we can use to move content horizontally and vertically.

translateX: This will move the contents horizontally.
translateY: This will move the contents vertically.

	
<Text style={{ fontSize: 20, transform: [{ translateX: 50 }] }}>
    Hello World!
    </Text>

In the above code, we are directly provided with a fixed value of 50. What happens if we can provide a changing value instead of this fixed value? It will create an animation on the screen.

Yes, if the transform value changes, it will reflect on the screen also because our content will move according to the value we are providing, and we can create some animations on the screen using that.
So using this animated library, we can create changing values or animated values.

For making an oscillating text horizontally, first, we need an initial value, say 0; then the value increases to 50; after reaching 50, it starts to decrease and reaches 0. Then the value again starts decreasing and reaches -50. After reaching the negative end, the value starts increasing.
If we can change such a value, we can create an oscillation effect on the screen.

Now we can make such a value using the Animated API.

Already, we have set our initial animated value to 0. Now we need to increase it. For that, we can use one method in the Animated library.

	
 Animated.timing(value, configuration)

So using this timing method, we can change our animated values concerning the time. It has two parameters; one is the value, which is an animated value. Another one is configuration.

	
const moveRightX = () => {
    Animated.timing(animatedValue, {
      toValue: 50,
      duration: 4000,
      useNativeDriver: false,
    })
  };

Here I have created a function named moveRightX which has a timing method.

So you can see that we have passed the animated value as the first parameter, which we have initialized into 0 before.

Next is the configuration part. As you see, toValue accepts a value we need at the end of the animation.

Also, we can provide the duration of the animation in milliseconds.

Here I have provided the duration as 4000 ms, which means our value will change from 0 to 50 in 4000 ms.

Also the third one,useNativeDriver: false, also tells us not to use the native driver for this animation.

So now we have a changing value from 0 to 50. What would happen if we provided this changing value to transform the property in style? Our text moves to the right. Let’s call this function in the useEffect and add this dynamic value to our component.

	
useEffect(() => {
    moveRightX();
  }, []);

<Animated.Text style={{fontSize:20,transform:[{translateX:animatedValue }]}}>
    Hello World!
 </Animated.Text>

You must notice that we have changed the normal into . Otherwise, it will show an error because we are using some animated values that do not support the normal . So we need to change it into .

Now you can see that your Text is moving to the right side and stops. You have done a simple animation now.

Output

But we need to make better-oscillating text to the right and left. For that, we need to take a few more steps.

Let’s create another function for creating a decreasing animated value.

	
const moveLeftX = () => {
    Animated.timing(animatedValue, {
      toValue: -50,
      duration: 4000,
      useNativeDriver: false,
    })
  };

Here you can see that you have given a negative value for toValue.So it will decrease the value to -50.

But one problem is that you must call this only after completing the first animation towards the right side. For that, we can use the start method here. We can attach a start method to our timing method. Thus we can do something right after the animation ends.

So we can make some changes to our initial function,

	
const moveRightX = () => {
    Animated.timing(animatedValue, {
      toValue: 50,
      duration: 4000,
      useNativeDriver: false,
    }).start(moveLeftX);
  };

You can see that we have added a start () method at the end. In that case, we are calling another function. You can perform any other codes here as you wish.

We can add a start() in the moveLeftX function. Thus, it will call moveLeftX at the end. By doing this, we are creating a changing or oscillating value.

If you look closely, you can see that your text is starting to oscillate in the right and left directions. You can adjust the duration as per your requirements. Thus, you can adjust the speed of the animation as you like.

Output

One more thing is that now we have given this animated value to the translateX property. If we provide this value to translateY, what would happen? The text would start moving vertically to the top and bottom. Let’s check that also.

	
<Animated.Text style={{fontSize:20,transform:[{translateY:animatedValue }]}}>
    Hello World!
 </Animated.Text>

Output

It’s not the end. You can do much more; suppose we provide this animated value to the fontSize; you can see some other interesting animation. Let’s check that also. I have removed the transform property and given the fontSize with our animated value. Now you see the text size is increasing and decreasing.

	
<Animated.Text style={{ fontSize: animatedValue }}>
    Hello World!
   </Animated.Text>

Output

Instead of this text, we can animate an image here. But remember, you should use , not the normal <Image> tag.

	
<Animated.Image
          source={{ uri: 'https://reactjs.org/logo-og.png' }}
          style={{ height: animatedValue, width: animatedValue }}
        ></Animated.Image>

In the above code, you can see that I have given an animated value for the height and width of the image. Thus, you can see an animated image on the screen.

Output

In this way, you can easily animate your content. This is a basic example for beginners. We can provide this animated value to other style properties, such as opacity, flex, etc. You can create animations by adjusting those values according to your needs.

Using this idea, you can create a header in which the height increases or the width increases and decreases. You only need to create a changing animated value for the header height or width.

If you provide this changing value to opacity, it will vary dynamically. But its range must be between 0-1.when the opacity reaches 0, the component will disappear. Thus you can create something which is appearing and disappearing. I have changed the toValue to 1,0 respectively in the following functions.Also added opacity in style and provided the animated value for the image.

	
const moveRightX = () => {
    Animated.timing(animatedValue, {
      toValue: 1,
      duration: 4000,
      useNativeDriver: false,
    })
  };
	
const moveLeftX = () => {
    Animated.timing(animatedValue, {
      toValue: 0,
      duration: 4000,
      useNativeDriver: false,
    })
  };
	
<Animated.Image
          source={{ uri: 'https://reactjs.org/logo-og.png' }}
          style={{ height: 200, width: 200, opacity: animatedValue }}
        ></Animated.Image>

Output

Following are the six components that you can use in Animated API.

1. Animated.Image
2. Animated.ScrollView
3. Animated.View
4. Animated.SectionList
5. Animated.Text
6. Animated.Flatlist

So in this section, we have learned some basic lessons for animations in React Native. There are many more methods and effects, which you can see in the React Native documentation.

I have given the basic codes for your reference below.

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


const Animation = ( ) => {


  const animatedValue = useRef(new Animated.Value(0)).current;


  const moveRightX = () => {
    Animated.timing(animatedValue, {
      toValue: 50,
      duration: 4000,
      useNativeDriver: false,
    }).start(moveLeftX);
  };
  const moveLeftX = () => {
    Animated.timing(animatedValue, {
      toValue: -50,
      duration: 4000,
      useNativeDriver: false,
    }).start(moveRightX);
  };
  useEffect(() => {
    moveRightX();
  }, []);

  return (
       <>
      <Animated.View
        style={[
          style.container,
          {
            justifyContent: 'center',
            alignItems: 'center',
            height: 400,
            backgroundColor: 'yellow',
          },
        ]}
      >


 <Animated.Text style={{ fontSize: animatedValue }}>
Hello World!
</Animated.Text>


        {/* <Animated.Image
          source={{ uri: 'https://reactjs.org/logo-og.png' }}
          style={{ height: animatedValue, width: animatedValue }}
        ></Animated.Image> */}
      </Animated.View>
    </>
  );
};


const style = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    margin: 0,
    flex: 1,
    paddingTop: 50,
    flexDirection: 'column',
  },
});
 export default Animation;

Schedule an interview with React developers

Conclusion

The Animated API in React Native offers a straightforward way to create basic animations within your mobile applications. By defining animated values and using various animation methods provided by the API, React developers can add life and interactivity to their apps, improving the overall user experience. Animations also make your app presentable, and users will like to interact with it.

If you are interested in animating your React Native app within the project, contact us to leverage our top-notch app development services. Feel free to connect with us; we will give you the preferred engagement model.

Frequently Asked Questions (FAQs)

1. What is the objective of the Animated API in React Native?

The Animated API provides a number of methods, such as sequence() and delay(), each of which accepts an array of the animations that will be executed and calls the start() or stop() function automatically as necessary. Hence, if one Animation is stopped or interrupted, all other animations in the group are also stopped.

2. What is an animated API?

Web animation APIs enable timing and synchronization adjustments to the presentation of web pages, i.e., DOM element animation. It does this by merging the two models, such as the timing and animation models.

3. How do I implement React Native Animations?

Animation in React Native can be integrated via the following steps:
Step 1: Import the animation module
Step 2: Declare the animated value
Step 3: Specify how an animated value will change over the time
Step 4: Set the animated style and renders the animated version of the component
Step 5: Finally, begins the Animation.


Book your appointment now

Request a Quote