DEV Community

Paul Oloyede
Paul Oloyede

Posted on

Can we Animate Opacity in React Native?

Image description


Introduction

Opacity means transparency of an object or element used to control the visibility of an element.

It helps with a gradual entrance and gradual exit to prevent any sort of jarring layout movements that may affect the user negatively. When change occurs for an opacity value, it affects the visibility of the component in which such change is been acted upon.

You can set opacity values from 0 to 1 which is equivalent to 0% to 100%. So for example, we can set our opacity value to 0.1, or 0.5 based on how much visibility or transparency we want or the message being conveyed to a user at the time.

Benefit of Animating Opacity

  • One of the core importance of animating this value when changed is to give the smooth transitioning effect to the eye of the user, basically not changing visuals in an unappealing manner. This can at times irritate the user.
  • Allow the user to see the effect of their action, and not living them to wonder if there was any at all.
  • Creating a connection between each state of your application.
  • it helps to convey or drive the message home with ease.
  • it can be used as a guide for the user when they need to perform some actions that are required. Take, for example, a button that can remain disabled until some form fields are filled and validated. it is often implemented by blurring out the button component until these actions or requirements are met.

Prerequisites

  • Basic knowledge of JavaScript
  • Basic knowledge of React
  • Basic knowledge of running CLI commands
  • Node.js and npm installed on your machine
  • XCode or Android Studio installed on your machine
  • Some experience with React Native (suggested, not required)

Getting Started

Let's create a new expo project using this command:

npx create-expo-app rn-opacity
Enter fullscreen mode Exit fullscreen mode

In the root of our application that we've just created, there is a App.js file that contains a starter code to show us the application is up and running properly after installation.


So let's run our app using this command yarn ios for iOS and yarn android for android devices respectively, we will see the content of the component appear on our screen.

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text>Open up App.js to start working on your app!</Text>
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Enter fullscreen mode Exit fullscreen mode

Building the UI

Can we add a component structure to demonstrate our example? Yes, that's possible!


In our source code is an orange box, where we use View component to build the UI and style the backgroundColor to orange


we import the react library on line 1.

On line 2 we import StyleSheet for writing external styles, View for building our UI, and TouchableWithoutFeedback button component for achieving interaction or state switch trigger.

import React from "react";
import { StatusBar } from "expo-status-bar";
import { StyleSheet, View, TouchableWithoutFeedback } from "react-native";

export default function App() {
  return (
    <View style={styles.container}>
      <TouchableWithoutFeedback onPress={() => null}>
        <View
          style={styles.box}
        ></View>
      </TouchableWithoutFeedback>

      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  box: {
            backgroundColor: "orange",
            height: 200,
            width: 200,
            opacity: 0.5,
          }
});

Enter fullscreen mode Exit fullscreen mode

Putting Everything Together

In our App.js file below, we have added quite many changes, let's go through the lines of code for explanation.



import React, { useRef } from "react";
import { StatusBar } from "expo-status-bar";
import {
  StyleSheet,
  View,
  TouchableWithoutFeedback,
  Animated,
} from "react-native";

export default function App() {

  const opacityAnimation = useRef(new Animated.Value(0.5)).current;


  const opacityStyle = { opacity: opacityAnimation };

  const animateElement = () => {

    Animated.timing(opacityAnimation, {
      toValue: 0,
      duration: 1500,
      useNativeDriver: true
    }).start(() => {
      Animated.timing(opacityAnimation, {
        toValue: 1,
        duration: 1500,
        useNativeDriver: true
      }).start()
    })
  };

  return (
    <View style={styles.container}>
      <TouchableWithoutFeedback onPress={() => animateElement()}>
        <Animated.View style={[styles.box, opacityStyle]}></Animated.View>
      </TouchableWithoutFeedback>

      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
  box: {
    backgroundColor: "orange",
    height: 200,
    width: 200,
    opacity: 0.5,
  },
});

Enter fullscreen mode Exit fullscreen mode

We declare an opacityAnimation variable to hold the Animated.value which is set to 0.5. This means that the opacity value of our box at default when rendering it's 0.5

While on line 13, in our code, we also declare a variable to hold an object for the opacity style we would be changing dynamically and we set the opacity property to the value of opacityAnimation.

In the animateElement function we access the Animated.timing method. Timing will specify the animation of a single value to another value over a set period, so its function signature is opacityAnimation and then the configuration object. In our config object we have the following options:

  • toValue: the new value we are animating to.
  • duration: lenght of animation in milliseconds
  • useNativeDriver: allows native code to perform the animation on the UI thread.

To trigger a change, we need to call start method as we have it in our source code.

Also where we are rendering our UI we have replaced the View component with Animated.View component. The Animated library wraps around the normal View element

The call the animateElement function in our TouchableWithoutFeedback button component. Where it is passed into the onPress function props.

Clicking within the box area would trigger our animations, allowing it to fade out from 0.5 to 0 and then fade in from 0 to 1 for 1500 milliseconds on both calls.

Here is a demo of the app:

Image description

Summary

A good use case where this can be applied is in a Button component, a Checkbox component, and a Radio Button component. You will find this implementation useful for achieving visual effects appealing to the user when interacting with your apps.

Thanks for stopping by, hope you find this tutorial useful.

Cheers!!!

Top comments (0)