The Beauty of React Native’s LayoutAnimation

User experience plays a vital role in success of your application, It helps keep end user engaged. A good user interface will create an instant attraction to your app while a great user experience will put a lasting impact on your users’ mind. Adding animations to your application is one way of achieving user attention to details you want to feature.
In order to do that you will need to learn to handle complex animations using React Native Animated API or any other library to help your cause.
But what if I tell you that there is a painless and an easy way to achieve this by just writing a few lines of code.

Consider a simple example where you have three blocks with dynamic heights, that change to some random number when you press a button.
The transition will look something like below

Changing heights without LayoutAnimation

The transition is not at all soothing to the eyes. With LayoutAnimations you can automatically animate the views when the next layout change happens.

Assuming you already have a React Native app setup and running (If you do not have, use this link), let us now write a few lines and see the magic.

STEP 1: Import the below classes

Import {LayoutAnimation, Platform, UIManager} from “react-native”

Step 2: You need to set the following flags via ( For Android)

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

Step 3: Call the following before your layout changes ( In our case before setState )

LayoutAnimation.configureNext(LayoutAnimation.Presets.linear);

The new transition will look something like this.

Preset- linear

Amazing isn’t it, by just following 3 simple steps you animated your views to give a much better transition effect. Now try it yourself and make sure to try all the three presets to see the difference in animation. You can get the complete code for the class below.

LayoutAnimation comes with three presets:

  • easeInEaseOut
  • linear
  • spring

Life-long learner | Enthusiastic | Software Developer