Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you show height in React Native?

In react native application, to set the dimensions of a component, we use width and height properties. Remember, all the values of dimensions are unitless like we can't use height: 20px to set the height of a component instead of we just use height: 20 and react-native automatically set the pixels.

How do you find the width and height in React Native?

state. view2LayoutProps. height + 1; const newLayout = { height: newHeight , width: width, left: x, top: y, }; this. setState({ view2LayoutProps: newLayout }); } render() { return ( <View style={styles.

How do I get dynamic height in React Native?

React Native provides a Dimensions API that can be used to get the width and the height of the window. From there on, you can compute the available height yourself by subtracting the size of the Toolbar and the TabMenu.


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.


Hi everyone, hope it's not too late...

for anyone who is dealing with React Native animation on view's height.
I know it is very annoying as:

✖️ React Native animation seems not supporting layout styles (e.g. width and height)
✖️ LayoutAnimation looks complicated to investigate
✖️ Wish to use an official way to animate instead of installing a third-party package
✖️ Sometimes content could be large to break your view styles

so here is my solution for you (class component way):

First, set the animated value in state:

state = { height: new Animated.Value(0) };

Next, set your animated view's max height with animation interpolation:

const maxHeight = this.state.height.interpolate({ 
  inputRange: [0, 1], 
  outputRange: [0, 2000]  // <-- any value larger than your content's height
};
return (<Animated.View style={[styles.box, { maxHeight: maxHeight }]} />); 
// any other fixed styles in styles.box

After that, set the animation inside the function you called,
or componentDidMount if you want it to show as soon as it rendered:

// or in any function that users interact
componentDidMount() {
  Animated.timing(this.state.formHeight, {
    toValue: 1,
    duration: 500,           // <-- animation duration
    easing: Easing.linear,   // <-- or any easing function
    useNativeDriver: false   // <-- need to set false to prevent yellow box warning
  }).start();
}

Be aware that don't set useNativeDriver to true as it is not supported on layout styles.


Sample

So below is a sample for you to interact with,
feel free to copy and paste to your React Native project to have a try:

import React, { PureComponent } from 'react';
import { Animated, Button, Easing, View, Text, StyleSheet } from 'react-native';

class AnimateBox extends PureComponent {
  state = { opacity: new Animated.Value(0), height: new Animated.Value(0) };

  showContent = () => {
    const { opacity, height } = this.state;

    Animated.timing(height, {
      toValue: 1,
      duration: 500,
      easing: Easing.linear,
      useNativeDriver: false  // <-- neccessary
    }).start(() => {
      Animated.timing(opacity, {
        toValue: 1,
        duration: 500,
        easing: Easing.linear,
        useNativeDriver: false  // <-- neccessary
      }).start();
    });
  };

  render() {
    const { opacity, height } = this.state;
    const maxHeight = height.interpolate({ 
      inputRange: [0, 1], 
      outputRange: [0, 1000]  // <-- value that larger than your content's height
    });

    return (
      <View style={styles.box}>
        <Animated.View style={{ opacity: opacity, maxHeight: maxHeight }}>
          <Text style={styles.content}>
            Lorem Ipsum is simply a dummy text of the printing and typesetting industry.
            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
            when an unknown printer took a galley of type and scrambled it to make a type specimen book.
            It has survived not only five centuries, but also the leap into electronic typesetting,
            remaining essentially unchanged. It was popularised in the 1960s with the release of
            Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
          </Text>
        </Animated.View>
        <View style={styles.spacing}>
          <Button title="Show content" onPress={this.showContent} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  box: {
    backgroundColor: '#fff',
    marginHorizontal: 15,
    paddingHorizontal: 15
  },
  spacing: {
    paddingVertical: 10
  },
  content: {
    fontSize: 16,
    lineHeight: 30,
    color: '#555'
  }
});


export default AnimateBox;

Happy Coding :)


More Explanation (Edit in 03 Feb 2021)

As mentioned in React Native documentation:
https://reactnative.dev/docs/animations#caveats

Not everything you can do with Animated is currently supported by the native driver. The main limitation is that you can only animate non-layout properties: things like transform and opacity will work, but Flexbox and position properties will not.

Disabling useNativeDriver can animate styles other than opacity and transform, but in fact increase the workload on JS thread as JS thread needs to calculate the UI on every frame.

And here in React Native 0.62's blog:
https://reactnative.dev/blog/2020/03/26/version-0.62#deprecations

Setting useNativeDriver is now required to support switching the default in the future.

You must need to set the useNativeDriver in animation options on React native v0.62 or above to prevent any warnings.


The method I've taken is to spend layout passes getting the height of the "truncated" component and the height of the "full size" component (you need a way for the truncated height to be deterministic, usually by knowing how to render a "row" of content). Essentially before you have those values, you render these as two separate views that are hidden:

hidden: {
  position: 'absolute',
  left: 0,
  top: 0,
  opacity: 0,
},

Use onLayout to capture their heights:

const onLayoutTruncated = ({nativeEvent}: LayoutChangeEvent) => {
  if (!doneProcessing) {
    truncatedHeight = nativeEvent.layout.height;
    checkIfDoneProcessingLayout();
  }
};

const onLayoutFull = ({nativeEvent}: LayoutChangeEvent) => {
  if (!doneProcessing) {
    fullHeight = nativeEvent.layout.height;
    checkIfDoneProcessingLayout();
  }
};

checkIfDoneProcessingLayout() will check if both truncatedHeight and fullHeight are set, and make a state change if they both are (doneProcessing = true).

From there you should unhide the truncated view and be able to animate between both height values using an Animated.Value and interpolation:

const expandingHeight = animatedValue.interpolate({
  inputRange: [0, 1],
  outputRange: [truncatedHeight, fullHeight],
});

Trigger the expanding/collapsing animation on click using Animated.timing

Animated.timing(animatedValue, {toValue: isExpanded ? 0 : 1, easing: SOME_EASING_FUNCTION, duration: SOME_DURATION}).start();