Search code examples
animationlayoutreact-nativereact-native-flexboxreact-animated

React Native: how to animate Views from being stacked vertically to horizontally


So, essentially, I have two Views stacked vertically to start and on a button press they need to be animated so the first View scoots to the left and the second View goes up and sits to the right of the first one. Seems easy enough to do with adjusting flex on the first View and changing top and left styling on the second View, looks great on IOS, however on Android this is causing problems with the second View being cut off on the bottom when it goes up (presumably because the View's flex or height isn't tall enough for the content, but unfortunately I can't change that because it messes up flex styling for the rest of the content beneath).

Any suggestions on how to approach this?

This may not be possible, but I'm wondering if there is a way, either with LayoutAnimation or the Animated API, to animate these Views from a flexDirection 'column' to 'row'? That would be crazy convenient.


Solution

  • LayoutAnimation is wonderful, folks! Simply toggle between 'column' and 'row' on state change as desired and LayoutAnimation takes care of the rest—super neat. Here's a simple example for anyone else with the same problem, hope it helps:

    export default class Test extends Component {
      constructor() {
        super();
        this.state = {
          toggleStyle: 'column',
        }
    
        if(Platform.OS === 'android'){
          UIManager.setLayoutAnimationEnabledExperimental(true);
        }
      }
    
      _onPress = () => {
        LayoutAnimation.configureNext(CustomLayoutAnimation.position);
    
        let direction = this.state.toggleStyle === 'row' ? 'column' : 'row'
        this.setState({toggleStyle: direction})
      }
    
      render() {
        return(
          <View style={{flex: 1}}>
          <View style={{flex: 1}} />
            <View style={{flex: 1, flexDirection: this.state.toggleStyle}}>
              <View style={{flex: 1, width:'100%', backgroundColor: 'blue'}} />
              <View style={{flex: 1, width:'100%', backgroundColor: 'green', justifyContent: 'center', alignItems: 'center'}}><Text onPress={() => this._onPress()}>Toggle</Text></View>
            </View>
            <View style={{flex: 1}} />
          </View>
        )
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>