Home > Mobile >  Change state in between two animations
Change state in between two animations

Time:12-25

I am trying to find a way to change text(which is tied to a hook) in between two animations. Essentially I want the sequence of events to go in this order:

fade out -> state change -> fade in

Currently the sequence goes like:

state change -> fade out -> fade in

Another way I was thinking of achieving the same effect would be simply adding a sort of CSS transition time, but I can't find the equivalent for React-Native.

I am quite new to React Native, so any help would be appreciated. Here is my code:

import React, { useState, } from 'react';
import { View, Text, Animated, TouchableOpacity } from 'react-native';


function App() {
  const fadeVal = useState(new Animated.Value(1))[0]

  const texts = ["first", "second", "third", "fourth"]
  const [textID, setTextID] = useState(0)
  
  const fadeIn = 
    Animated.timing(fadeVal, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true
    })
  
  const fadeOut = 
    Animated.timing(fadeVal, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true
    })

  function bothAtOnce() {
      Animated.stagger(500, [fadeOut, fadeIn]).start()
      setTextID(textID   1)
  }


  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Animated.Text
        style={
          {
            width: 100,
            textAlign: 'center',
            justifyContent: 'center',
            opacity: fadeVal,
            backgroundColor: 'black',
            color: 'white'
          }
        }
        >
          {texts[textID]}
        </Animated.Text>
        <TouchableOpacity onPress={bothAtOnce}>
          <Text>Next</Text>
        </TouchableOpacity>
    </View>
  )
}

export default App;

CodePudding user response:

The start function that animations have accepts a callback. So you could totally go

  function bothAtOnce() {
    fadeOut.start(() => {
      setTextID(textID   1);
      // it happens kinda of instantly so
      // you might want to add a delay?
      fadeIn.start();
    });
  }

link

  • Related