Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React Native Animate to change view flex from 0 to 1

I have two views inside another view which has default flexDirection style so it is columnar. When the user clicks on an item in the bottom view (marked options below), I want the top view to animate to to be equal sizes with the bottom view and display the details of the selected option.

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

...

<View style={{flex: 1}}>
  <Animated.View style={{ flex: this.state.animation}}>
      {...details}
  </Animated.View>
  <View style={{flex:1}}>
      {...options}
  </View>
</View>

I am using the below method to change the value to grow the flex to 1.

onPress = () => {
    Animated.timing(this.state.animation, {
        toValue: 1,
        duration: 1000
    }).start()
}

The issue I am running into is there is no animation, it just instantly appears no matter the duration I set.

like image 252
wizloc Avatar asked Aug 15 '18 14:08

wizloc


People also ask

What does flex 1 do React Native?

Normally you will use flex: 1 , which tells a component to fill all available space, shared evenly amongst other components with the same parent. The larger the flex given, the higher the ratio of space a component will take compared to its siblings.

How do I add React animation to state change?

You can use CSS classes to animate in React import React, { useState } from 'react'; import classNames from 'classnames'; import styles from './App. module. css'; const App = () => { const [animate, setAnimate] = useState(false); const handleClick = () => setAnimate(!

What is flexGrow in React Native?

flexGrow describes how any space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children.


1 Answers

This works for me on expo:

export default class App extends React.Component {

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

onPress = () => {
    Animated.timing(this.state.animation, {
        toValue: 100,
        duration: 1000
    }).start()
}

  render() {
    return (
     <TouchableOpacity style={{flex: 100}} onPress={this.onPress}>
       <Animated.View style={{ flex: this.state.animation, backgroundColor:'blue'}}>
       </Animated.View>
       <View style={{flex:100, backgroundColor:'red'}}>
      </View>
    </TouchableOpacity>
    );
  }
}

Here is a working example: https://snack.expo.io/S1t5OaWL7

But I guess yes safer to animate height for performances. Not sure how flex is interpreted.

like image 69
Kevin Amiranoff Avatar answered Oct 21 '22 19:10

Kevin Amiranoff