Joshua Bitton
Joshua Bitton

Reputation: 403

React native animation opacity and position

I want to create an animation in my app, which includes transitioning the position and the opacity of a view. For now, all i have is transitioning the view, which I've done like so:

const fadeAnim = useRef(new Animated.Value(0)).current
useEffect(()=> {
  Animated.timing(
    fadeAnim,
    {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true,
      delay: 2000,
    }
  ).start();
}, [fadeAnim])

<Animated.View style={{
     opacity: fadeAnim
  }}>
{content}
</Animated.View>

How can I edit this to also transition the position, and then after a few seconds, I would like to hide this container.

Upvotes: 3

Views: 4815

Answers (1)

dianaqqq
dianaqqq

Reputation: 668

I would recommend to have a more general function for animations, so you can put it inside a separate file and use it wherever you need it. Something like this:

 const opacityRef = useRef(new Animated.Value(0)).current
 const translateRef = useRef(new Animated.Value(0)).current

 const initialX = 0
 const finalX = 100 // these values should be put inside constants so you'll have to change them if you need to only in one place
 
 
  // this is a general animation function, you can use it for opacity, translations, rotations
  const animateView = (toValue: number, animatedRef: Animated.Value, duration: number, delay: number) => {
    return Animated.timing(
      animatedRef,
      {
        toValue,
        duration,
        useNativeDriver: true,
        delay,
      }
    )
  } 


  // you can implement sequences of animations or even parallel if you need to (take a look at the docs)
   useEffect(()=> {
    Animated.sequence([
      animateView(finalX, translateRef, 1000, 0),
      animateView(initialX, translateRef, 1000, 0),
      animateView(0, opacityRef, 1000, 2000),
      animateView(1, opacityRef, 1000, 0),

    ]).start()

  }, [])
  
  
   return (
    <Animated.View style={{
      backgroundColor: 'red',
      width: 100,
      height: 100,
      left: 0,
      opacity: opacityRef,
      transform: [{
        translateX: translateRef
      }]

    }}/>
  )

Upvotes: 2

Related Questions