Victor Molina
Victor Molina

Reputation: 2661

React Native - Animate text from left to center of screen

How can I move this text from left to center using react native Animated API?

const animate = () => {
   // TODO - Animate text from 27.5 left, to center of screen
}

return (
   <View style={styles.header}>
      <Animated.Text style={{ marginLeft: 27.5 }}>
         Header
      </Animated.Text>
   </View>
);

Upvotes: 1

Views: 3146

Answers (1)

filipemelo032
filipemelo032

Reputation: 133

I righly recommend you to read the official React Native's Documentation: https://reactnative.dev/docs/animated

You can start by creating a reference from an animated value, like so:

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

And pass it to your animated componente:

...
 <Animated.Text style={[styles.text, {marginLeft: moveAnimation}]}>
...

Finally, we need to create your animation:


// Note that i used Dimensions from React-Native and subtracted 50 from it
// because i have a padding in my View component

const animate = () => {
    Animated.timing(moveAnimation, {
      toValue: (Dimensions.get('window').width/2)-50,
      duration: 200
    }).start();
  }

Now, you can simply call our animate function to trigger it.

I wrote this Snack so you can see it running: https://snack.expo.io/@filipemelo032/animation

Upvotes: 1

Related Questions