Search code examples
javascriptreact-nativeanimationmobilereact-animated

Animated.View only works on expanding, not on collapsing


I am having trouble using <Animated.View />. The following only works on when the toValue is set to 40. It expands nicely and the animation works. On collapsing (setting the toValue to 0), it just blends out - as if the visibility is set to none. Why is that?

const Foo = () => {
    const [bounceValue, setBounceValue] = useState(new Animated.Value(0));
    const [collapsed, setCollapsed] = useState(true);
    const height = { height: bounceValue };
    
    const _slideInOut = () => {
        let toValue;
        if (collapsed) {
            toValue = 40;
            setCollapsed(false);
        } else {
            toValue = 0;
            setCollapsed(true);
        }
        Animated.timing(bounceValue, {
            toValue: toValue,
            duration: 400,
            useNativeDriver: false
        }).start();
    }

    return <TouchableOpacity
        activeOpacity={1}
        style={[
            styles.container,
            ...
        ]}
        onPress={() => _slideInOut()}>
        <Animated.View
            style={[
                height,
                styles.menu,
            ]}>
            ...
        </Animated.View>
    </TouchableOpacity>
}

const styles = StyleSheet.create({
    container: {
        width: '100%',
        top: 0,
        height: 10,
        position: 'absolute',
    },
    menu: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: 'white',
        position: 'absolute',
        top: 10,
        width: '100%'
    }
})

Solution

  • you want to use a ref for this:

    const bounceValue = useRef(new Animated.Value(0)).current;