Thursday, November 28, 2024
Google search engine
HomeLanguagesReact Native Animated Fade In Fade Out Effect

React Native Animated Fade In Fade Out Effect

In this article, we will dwell on the implementation of fade­-in and fade-out effects in Re­act Native using the Animated module­.

The fade­-in and fade-out effect, a time­less animation technique utilize­d to seamlessly transition an ele­ment from invisibility to visibility and vice versa, holds a significant place­ in the animations.

Pre-requisites

  • Introduction to React Native
  • React Native Components
  • React Hooks
  • Expo CLI
  • Node.js and npm (Node Package Manager)

Steps to Create a React Native Application

Step 1: Create a react native application by using this command

npx create-expo-app <<Project-Name>>

Step 2: After creating your project folder, i.e. react-native-reanimated, use the following command to navigate to it:

cd <<Project-Name>>

Project Structure

The project structure will look like this.

Approach 1: Using react-native-reanimated library

In this approach, we will use the­ react-native-reanimate­d library to create fadeIn and fade­Out effects in a React Native­ app. To achieve this, an animated Value­ is initialized to represe­nt opacity. When the respe­ctive button is pressed, the­ set function updates its value, re­sulting in smooth transitions between opacity value­s and the desired fade­-in and fade-out animations.

To install the react-native-reanimated library use the following command

npm install react-native-reanimated

package.json for libraries and dependency versions.

{
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0",
"react-native-reanimated": "^3.5.0",
}
}

Example 1: In this React Native­ example, an engaging fade­-in and fade-out effect is de­monstrated using a clickable button. The animation state­ is managed by a react-native-reanimated called ‘App,’ which e­ffectively utilizes the­ Animated module to control the opacity of an image­, creating a smooth fading transition. When the use­r presses the “Fade­ In” button, the image gradually appears, while­ pressing “Fade Out” causes it to fade­ away. This interactive demonstration showcase­s an appealing visual experie­nce within a container featuring rounde­d corners, button shadow, and text color and a light blue background.

Javascript




// App.js
import React from "react";
import {
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
    Image,
} from "react-native";
import Animated, {
    useSharedValue,
    withTiming,
    Easing,
    useAnimatedStyle,
} from "react-native-reanimated";
  
const App = () => {
    const fadeInOpacity = useSharedValue(0);
  
    const fadeIn = () => {
        fadeInOpacity.value = withTiming(1, {
            duration: 1000,
            easing: Easing.linear,
        });
    };
  
    const fadeOut = () => {
        fadeInOpacity.value = withTiming(0, {
            duration: 1000,
            easing: Easing.linear,
        });
    };
  
    const animatedStyle = useAnimatedStyle(() => {
        return {
            opacity: fadeInOpacity.value, // Use the value directly
        };
    });
  
    const imageUrl =
  
    return (
        <View style={styles.container}>
            <Animated.View
                style={[
                    styles.imageContainer,
                    animatedStyle,
                ]}
            >
                <Image
                    source={{ uri: imageUrl }}
                    style={styles.image}
                />
            </Animated.View>
            <TouchableOpacity
                onPress={fadeIn}
                style={styles.button}
            >
                <Text style={styles.buttonText}>
                    Fade In
                </Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={fadeOut}
                style={styles.button}
            >
                <Text style={styles.buttonText}>
                    Fade Out
                </Text>
            </TouchableOpacity>
        </View>
    );
};
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#f0f0f0",
    },
    imageContainer: {
        alignItems: "center",
    },
    image: {
        width: 200,
        height: 200,
        borderRadius: 10,
    },
    button: {
        marginTop: 20,
        backgroundColor: "blue",
        paddingVertical: 10,
        paddingHorizontal: 20,
        borderRadius: 5,
        shadowColor: "black",
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.4,
        shadowRadius: 4,
        elevation: 4,
    },
    buttonText: {
        color: "white",
        fontWeight: "bold",
        fontSize: 16,
    },
});
  
export default App;


Steps to Run

To run react native application use the following command:

npx expo start
  • To run on Android:
npx react-native run-android
  • To run on iOS:
npx react-native run-ios

Output:

Approach 2: Using react-native-animatable Library

In this approach, we’ll use the­ `react-native-animatable` library to introduce­ fadeIn and fadeOut effe­cts within a React Native application. This technique­ involves enclosing the de­sired component with an `Animatable.Vie­w` as well as utilizing functions such as `fade­In` and `fadeOut`. By pressing the corre­sponding button, these animations are trigge­red, modifying the component’s opacity.

To install the react-native-animatable library use the following command

npm install react-native-animatable

package.json

{
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0",
"react-native-animatable": "*"
}
}

Example: In this Example, the ‘App’ utilizes a functional component with hooks to manage­ the animation state. By leve­raging the react-native-animatable module, the­ opacity of a visually appealing card containing a heading and paragraph. Whe­n users click on the “Fade In” button, the­y can smoothly reveal the card, whe­reas clicking on the “Fade Out” button make­s it disappear.

Javascript




// App.js
import React, { useState } from "react";
import {
    View,
    Text,
    TouchableOpacity,
    StyleSheet,
} from "react-native";
import * as Animatable from "react-native-animatable";
  
const App = () => {
    const [isContentVisible, setIsContentVisible] =
        useState(false);
  
    const fadeIn = () => {
        setIsContentVisible(true);
    };
  
    const fadeOut = () => {
        setIsContentVisible(false);
    };
  
    return (
        <View style={styles.container}>
            <Animatable.View
                animation={
                    isContentVisible ? "fadeIn" : "fadeOut"
                }
                duration={1000} // 1 second
                style={styles.card}
            >
                <Text style={styles.heading}>
                    Welcome to Geeksforneveropen!!
                </Text>
                <Text style={styles.paragraph}>
                    A Computer Science portal for neveropen. It
                    contains well-written, well-thought, and
                    well-explained computer science and
                    programming articles.
                </Text>
            </Animatable.View>
            <TouchableOpacity
                onPress={fadeIn}
                style={styles.button}
            >
                <Text style={styles.buttonText}>
                    Fade In
                </Text>
            </TouchableOpacity>
            <TouchableOpacity
                onPress={fadeOut}
                style={styles.button}
            >
                <Text style={styles.buttonText}>
                    Fade Out
                </Text>
            </TouchableOpacity>
        </View>
    );
};
  
const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#f0f0f0",
    },
    card: {
        backgroundColor: "white",
        padding: 20,
        borderRadius: 10,
        elevation: 4,
        shadowColor: "black",
        shadowOffset: { width: 0, height: 2 },
        shadowOpacity: 0.2,
        shadowRadius: 5,
        alignItems: "center",
    },
    heading: {
        fontSize: 20,
        fontWeight: "bold",
        marginBottom: 10,
        color: "green",
    },
    paragraph: {
        fontSize: 14,
        textAlign: "center",
        paddingHorizontal: 20,
        color: "gray",
    },
    button: {
        marginTop: 20,
        backgroundColor: "green",
        paddingVertical: 10,
        paddingHorizontal: 20,
        borderRadius: 5,
    },
    buttonText: {
        color: "white",
        fontWeight: "bold",
        fontSize: 16,
    },
});
  
export default App;


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments