Code Whisperer
Code Whisperer

Reputation: 23652

Animating a View In React Native

I have a simple application with navigation and one component.

export default function App() {

  const Stack = createStackNavigator();

  return (

      <NavigationContainer>

            <Logo/>

            <Stack.Navigator>

                <Stack.Screen name="Home" component={HomeScreen} />
                <Stack.Screen name="Details" component={DetailsScreen}/ >

            </Stack.Navigator>

      </NavigationContainer>

  );

}

The HomeScreen component has a simple fade animation that trigger when the application starts.

export const HomeScreen = ({navigation})=>{

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

    React.useEffect(() => {
        Animated.timing(
          fadeAnim,
          {
            toValue: 1,
            duration: 350,
          }
        ).start();
      }, [fadeAnim]);

    return (
        <Animated.View style={{opacity: fadeAnim}} >
            <Text>
                Hello World
            </Text>
        </Animated.View>
    )
    
  }

The problem is that the fadeAnim animation does NOT restart when the view changes. Loading the "details" screen and then the "home" screen again finds the component in its final state.

How can I make the "home" screen fade in every time?

Not sure if the right solution is with react-native or react-native-navigation, but a solution involving either would be great.

Upvotes: 1

Views: 493

Answers (1)

Jacob
Jacob

Reputation: 1395

Try using useFocusEffect

import { useFocusEffect } from '@react-navigation/native';

function HomeScreen() {
  const [fadeAnim] = useState(new Animated.Value(0));

  useFocusEffect(
    React.useCallback(() => {
      Animated.timing(
        fadeAnim,
        {
          toValue: 1,
          duration: 350,
        }
      ).start();
    }, [fadeAnim])
  );

  return yourComponents;
}

Upvotes: 1

Related Questions