How do you animate the height in react native when you don't know the size of the content?

In react-native, how do you animate the size of a View when you dont know the size of it's contents?

Let's say the View's content height can be anywhere from 0-400pts, and the content can grow and shrink dynamically, and you want to animate any changes to the height.

Basically, I'm looking to reproduce the behaviour of LayoutAnimation without using LayoutAnimation but using Animated.

I think what eludes me is I don't know how to animate towards a target height since I don't know the height of the content.


I use LayoutAnimation for that, just before the state change that causes your component's height to change, add:

LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);

You can use different presets:

  • spring
  • easeInEaseOut
  • linear

    You can read more about it here https://facebook.github.io/react-native/docs/layoutanimation.html


You are going to have to add some kind of size scaling, probably with percentages for best effect.

First thing first you would need to use Animated.View instead of View.

Next you would need to apply a transform to the style of the view lets say it looks like below. This is the part that updates and changes and creates the motion.

        <Animated.View style={[ styles.someStyleYouMade,
          {
            transform: [
              // scaleX, scaleY, scale, theres plenty more options you can find online for this.
              {  scaleX: ViewScaleValue } // this would be the result of the animation code below and is just a number.
            ]
          } 
        ]}
        >

This next part is basically an animated API example, you would write something like this (custom to how you want) and when this script is called it will animate in whatever way you specify.

  Animated.timing(                    // Animate over time
    this.state.ViewScale,             // The animated value to drive, this would be a new Animated.Value(0) object.
    {
      toValue: 100,                   // Animate the value
      duration: 5000,                 // Make it take a while
    }
  ).start();

Lastly you will probably want to apply an interpolation to the value to make it look as custom as possible.

(this will go into your render() function but before the return(). the ViewScaleValue will go into the Animated.View transform)

const ViewScaleValue = this.state.ViewScale.interpolate({
  inputRange: [0, 25, 50, 75, 100],
  outputRange: [0, .5, 0.75, 0.9, 1]
});

all of this code would make ViewScaleValue, a simple number, animate from 0-100, going fast and then slow (because of interpolation) and apply each iteration of the animation to the Animated.View transform.

Read the Animated API alongside this to get a good grasp on it.