Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native animation opacity and position

Tags:

react-native

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.

like image 258
Joshua Bitton Avatar asked Dec 31 '25 07:12

Joshua Bitton


1 Answers

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
      }]

    }}/>
  )
like image 81
dianaqqq Avatar answered Jan 04 '26 16:01

dianaqqq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!