Search code examples
reactjsreact-nativereact-animatedreact-native-animatable

React-Native Animate View In and Out


Currently, I am struggling with appearing and disappearing animations.. My aim is to animate a view in and again out.. but I want also that the view does 100% disappear after the animation

Idea

    ...

const visible: boolean = props.visible || false;
const [showView, setShowView] = useState<boolean>(visible);
const viewAnimation = useRef<Animatable.View & View>(null);

   useEffect(() => {
        const Animation = async () => {

            if (visible) {
                setShowView(true);
                if (viewAnimation.current)
                    await viewAnimation.current.bounceIn(2000);
            } else {
                if (viewAnimation.current)
                    await viewAnimation.current.bounceOut(2000);
                setShowView(false)
            }
        }

        Animation();
    }, [visible, viewAnimation]);

...

{showView &&
<Animatable.View ref={viewAnimation}>
...
</Animatable.View>
}

...

Problem The viewAnimationRef get set in the next render cycle and not instant after setting the showView to true -> the bounceIn animation will never get executed.. because viewAnimation.current is null..

I am using:

  • react-native 0.62
  • react-native-animatable 1.3.3

Maybe sb has an idea how to solve this problem ^^

Thank you


Solution

  • The solution is simple just wrap the Animatable.View around a normal view and hide the normal view if you want to hide it

    Example:

        ...
    
    const visible: boolean = props.visible || false;
    const [showView, setShowView] = useState<boolean>(visible);
    const viewAnimation = useRef<Animatable.View & View>(null);
    
       useEffect(() => {
            const Animation = async () => {
    
                if (visible) {
                    setShowView(true);
                    if (viewAnimation.current)
                        await viewAnimation.current.bounceIn(2000);
                } else {
                    if (viewAnimation.current)
                        await viewAnimation.current.bounceOut(2000);
                    setShowView(false)
                }
            }
    
            Animation();
        }, [visible, viewAnimation]);
    
    ...
    
    
    <Animatable.View ref={viewAnimation}>
    {showView &&
    <View>
    ...
    </View>
    }
    </Animatable.View>
    
    
    ...