This content originally appeared on CodeSource.io and was authored by Codesource Staff
A key part of building applications with great user experience is the ability to synchronize the flow of the application with activities performed at any point in time.
Creating a smooth connection in the application gives a meaningful user experience that allows for ease of interaction.
For this purpose, representing an action well in modern mobile applications cannot be over-emphasized, which brings us to one of the components that are used in communicating with the users in other to act, The Slide Toggle.
The Slide toggle is a common component in most interfaces today. A Slide toggle must work as the user expects it to.
The slide toggle is a representation of a physical switch that allows users to turn things on or off. Most common toggles are used to switch between on/off in preferences, settings, or turning on/off Wi-Fi on a smartphone.
The purpose of this guide is to demonstrate how to build an animated slide toggle in React native.
At the end of the guide, you will be able to build an animated slide toggle while understanding the underlining concept of building this feature. This tutorial tends not to leave any stone unturned, so do well not to skip any sections.
Since this is a how-to article, it’s important to know what kind of environment you need prior to getting started. If you’d like to follow along with the rest of this article, ensure you have the following prerequisites in place.
Pre-requisites
Tools and technology stack required to follow through this article:
- knowledge of JavaScript
- knowledge of React
- knowledge of running command line/terminal instructions
- Node.js and npm installed on your machine
- XCode or Android Studio installed on your machine
- Some experience with React Native
For this article, the React library is used in creating a user interface (UI). React library is created by Meta(Facebook) as a frontend framework built with the JavaScript programming language.
React Native, the mobile application framework we are using is built with the React library. Also, this tutorial uses the Expo framework. Expo is a cross-platform framework for React Native to build once and publish everywhere (iOS, Android, and Web).
If you are new to the ecosystem you may want to start from the React Native Guide.
So let’s head straight to the setup phase of creating the slide toggle.
Getting Started
Open a command prompt window, and navigate to where you will like to save your application from the command prompt. Enter the following command to create a new application:
npx create-expo-app rn-slide-toggle
Once the application has been created, navigate to the rn-slide-toggle folder, you will see a couple of files created in the root of the project.
In the root of the application, there is an App.js file that contains a starter code.
Running the yarn ios
for iOS device and yarn android
for android device command would instruct the React native compiler to bundle the code and display the user interface.
This is what you should see on the screen:
Alright, before we proceed with coding out the feature, let’s examine some terms used for clarity.
Defining Terminologies
A key concept that could help achieve our animated slide toggle is the concept of translation. Translation means moving an element/item from one position to the other.
You can translate a component using the transform style property in react native. The transform style takes an array of objects with key-value pairs containing the different axis from which we can control the positioning of an element.
Quick Notes
- Do not forget the importance of timing when translating elements.
- We have the importance of timing. Regardless of the intent behind your animation, translation has to adjust to the visual and stylistic template you have set. If the translation gets so long that you’re losing audiences, it’s always better to simplify.
- Pay attention to proper timing.
Translation forms the backbone of what we intend to achieve in this tutorial. Let’s move on to the next section.
Importing Libraries
So in your App.js
file replace the code in there with the one below. As we gradually go through the code to understand things in bits and pieces.
On the very first line import the React library into your App.js
file, also import, the useRef
and useState
hooks for storing and accessing state variables in the component.
While on the next line we bring in some components from the react-native package needed in building the user interface.
import React, { useRef, useState } from "react";
import {
StyleSheet,
View,
TouchableWithoutFeedback,
Animated
ImageBackground,
} from "react-native";
// code omitted for brevity
In diving deep into the implementation of the slide toggle, let’s go through the next step below, which involves more code.
Creating The Slide Toggle
Inside the App()
component, define a const variable, translateAnimate
, to store the Animated.Value
. Set Animated.Value
to 0.
Prepend the Animated.Value
with the new keyword to create an instance of the object.
To avoid to unnecessary re-rendering in the app, pass the new Animated.Value(0)
into the useRef
hooks.
//... imports omitted for brevity
export default function App() {
const translateAnimate = useRef(new Animated.Value(0)).current;
const [isToggle, setIsToggle] = useState(false);
const animateInterpolate = translateAnimate.interpolate({
inputRange: [0, 1],
outputRange: [0, 46],
});
const animateElement = () => {
const toValue = isToggle ? 0 : 1;
Animated.timing(translateAnimate, {
toValue,
duration: 500,
useNativeDriver: true,
}).start(() => {
setIsToggle(!isToggle);
});
};
const animationStyle = {
transform: [
{
translateX: animateInterpolate,
},
],
};
// code omitted for brevity
}
The animateInterpolate
variable holds the value for the interpolate configuration object. Add the inputRange
, and outputRange
properties to the object. Each property takes an array of a range of values respectively.
Give the inputRange
an array with values of 0 and 1. Also, give the outputRange an array with values of 0
and 46
.
So, while at 0
in the inputRange
, the outputRange
is set to 0
, which is the default position of the element in the application.
A change in the value of inputRange from 0
to 1
would update the outputRange from 0
to 46
.
These values from the outputRange
are passed into the Animated.View
which you will see a bit.
Inside the animateElement
function create const a variable, toValue. toValue takes a conditional statement to set it’s value to 0
when isToggle
is true or 1 when isToggle
is false.
Also, in the animateElement
function add the Animated.timing
method. Pass in the translateAnimate
as the first argument, and the configuration option as the second.
You have to update the isToggle
variable whenever we call start method. In the start method update the isToggle
state variable by calling the setIsToggle
function declared with the useState
hook.
Now let’s connect the logic above to the user interface, bringing the slide toggle to live!
Building the User Interface
The ImageBackground
element is the wrapper for the entire user interface(UI).
Add the TouchableWithoutFeedback
button component, which is the action trigger for the slide toggle.
Inside the TouchableWithoutFeedback
we have a child element, the View item.
Insert the Animated.View
component as an inner element into the View item. The Animated.View
is a View component wrapped by the Animated library. This makes the View component animateable.
Here in the code below, you will see the onPress props in the TouchableWithoutFeedback calls the animateElement function. Ensure not to skip that too.
Here is the code:
// imports omitted for brevity
export default function App() {
// code omitted for brevity
return (
<ImageBackground
source={require("./assets/home.jpg")}
style={styles.container}
>
<TouchableWithoutFeedback onPress={() => animateElement()}>
<View style={styles.toggleContainer}>
<Animated.View
style={[styles.toggle, animationStyle]}
></Animated.View>
</View>
</TouchableWithoutFeedback>
</ImageBackground>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
toggleContainer: {
borderRadius: 20,
borderWidth: 0,
height: 35,
width: 80,
backgroundColor: "grey",
justifyContent: "center",
paddingHorizontal: 2
},
toggle: {
backgroundColor: "blue",
height: 30,
width: 30,
borderRadius: 16,
borderWidth: 0,
},
});
Putting Everything Together
Waooh! we’ve come a long way, if you made it this far, well done, you are doing great!
Putting it all together, this is the complete code.
import React, { useRef, useState } from "react";
import {
StyleSheet,
View,
TouchableWithoutFeedback,
Animated, // import the animated libriary
ImageBackground,
} from "react-native";
export default function App() {
const translateAnimate = useRef(new Animated.Value(0)).current;
const [isToggle, setIsToggle] = useState(false);
const animateInterpolate = translateAnimate.interpolate({
inputRange: [0, 1],
outputRange: [0, 46],
});
const animateElement = () => {
const toValue = isToggle ? 0 : 1;
Animated.timing(translateAnimate, {
toValue,
duration: 500,
useNativeDriver: true,
}).start(() => {
setIsToggle(!isToggle);
});
};
const animationStyle = {
transform: [
{
translateX: animateInterpolate,
},
],
};
return (
<ImageBackground
source={require("./assets/home.jpg")}
style={styles.container}
>
<TouchableWithoutFeedback onPress={() => animateElement()}>
<View style={styles.toggleContainer}>
<Animated.View
style={[styles.toggle, animationStyle]}
></Animated.View>
</View>
</TouchableWithoutFeedback>
</ImageBackground>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
toggleContainer: {
borderRadius: 20,
borderWidth: 0,
height: 35,
width: 80,
backgroundColor: "grey",
justifyContent: "center",
paddingHorizontal: 2
},
toggle: {
backgroundColor: "blue",
height: 30,
width: 30,
borderRadius: 16,
borderWidth: 0,
},
});
Output below:
Conclusion
We’ve been able to build an Animated slide toggle component in this tutorial. Not only have you built a slide toggle, but you’ve also learned how to animate a slide toggle in react native.
Thanks for taking the time to read, sincerely enjoyed writing this blog post, hopefully, you enjoyed it too!
This content originally appeared on CodeSource.io and was authored by Codesource Staff
Codesource Staff | Sciencx (2022-10-30T12:55:57+00:00) How to Build an Animated Slide Toggle in React Native. Retrieved from https://www.scien.cx/2022/10/30/how-to-build-an-animated-slide-toggle-in-react-native-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.