Paul Oloyede I’m a highly motivated mobile developer who focuses on quality, maintainability, and efficiency. I enjoy lecturing, speaking at conferences, and writing about technology and development. I find that I can be more effective by empowering others to do better.

How to build an animated slide toggle in React Native

7 min read 1978

How to Build an Animated Slide Toggle in React Native

In this guide, we’ll learn how to build an animated slide toggle in React Native and understand the underlining concepts of creating this feature.

As technology and the human race have progressed, our lives have become intertwined with our use of technology. Many applications strive to interpret everyday life into applications, bridging the gap between two worlds. One such relationship between real-world and mobile applications is the interpretation of object states.

Often, we like to create the look and feel of these real-world scenarios in our applications. This means that an integral part of building applications with great UX is connecting the application flow with activities performed at any time. Creating a smooth connection in the application creates meaningful UX and increases a user’s ease of interaction. Therefore, it’s important to represent an action well in modern mobile applications.

This tutorial will leave no stone unturned, so do not skip any sections!

 

Jump ahead:

What is an animated slide toggle?

A slide toggle represents a physical switch that allows users to turn things on or off. Most toggles are used to switch between on/off in preferences and settings or toggle Wi-Fi on a smartphone. Slide toggles are also best used for changing the state of system functionalities and preferences.

Since this is a how-to article, knowing what kind of environment you need before getting started is essential. If you are new to the ecosystem, it may help to start from the React Native docs.

Prerequisites

To follow this tutorial, you will need the following:

So, let’s head straight to the setup phase for the guide.

Getting started in React Native

First, open a command prompt window, and navigate to where you would like to save your application from the command prompt. Then, 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, where you will see a couple of files created at the root of the project. In the root of the application, there is an App.js file that contains a starter code.

Running yarn ios for iOS devices and yarn android for Android device command will instruct the React Native compiler to bundle the code and display the user interface:

Starting the React Native App

Alright, before we proceed with coding out the feature, let’s examine some terms used for clarity.

Understanding the concepts of animated slide toggles in React Native

A key concept to help us achieve our animated slide toggle is 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. Transform takes an array of objects with key-value pairs containing the different axis from which we can control the positioning of an element:

Do not forget the importance of timing when translating elements. Regardless of your animation’s intent, translation must 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. So, pay attention to proper timing!

Let’s look at an example of using the Switch component from React Native to create an animated slide toggle.



Building the built-in slide toggle in React Native

In this section, we’ll examine a minimalistic approach for implementing an animated slide toggle using the built-in switch component in React Native.

First, start by importing the components as follows:

// component state management
import React, { useState } from "react";
import { View, Switch, StyleSheet, Text } from "react-native";
import { StatusBar } from "expo-status-bar";

The isWifiEnabled variable inside the BuildInSlideToggle() holds the Boolean value for keeping track of the toggle state, which can be updated with the setIsWifiEnabled function. When the user clicks the slide toggle button, the wifiToggleSwitch() is called, and an update to the isWifiEnabled value is performed.

Notably, in the return statement, I am rendering the UI with the View and Text components, then passing in the style props to make it more aesthetically pleasing.

In the Switch, we will pass in the wifiToggleSwitch() into the onValueChange props that update and trigger a reaction whenever there is an action:

const BuiltInSlideToggle = () => {

  // define a isWifiEnabled state variable and set the default value to false
  const [isWifiEnabled, setIsWifiEnabled] = useState(false);

  // Handle changing the isWifiEnabled when button is clicked
  const wifiToggleSwitch = () =>
    setIsWifiEnabled((previousState) => !previousState);

  // Render a view with different style classes
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerText}>Settings</Text>
      </View>
      <View style={styles.option}>
        <Text style={styles.optionText}>Wifi</Text>
        <View style={styles.subOptionContainer}>
          <Text>Current Status is {isWifiEnabled ? "On" : "Off"}</Text>
          <Switch
            trackColor={{ false: "#767577", true: "#81b0ff" }}
            thumbColor={isWifiEnabled ? "#f5dd4b" : "#f4f3f4"}
            ios_backgroundColor="#3e3e3e"
            onValueChange={
              wifiToggleSwitch
            } /** call the wifiToggleSwitch when onValueChange callback */
            value={isWifiEnabled}
          />
        </View>
      </View>
      <StatusBar style="dark" />
    </View>
  );
};

React Native uses StyleSheet API to style and layout content in the UI. To use the appropriate styles in the code, access the styles variable assigned to hold the style object values from StyleSheet.

Then, add the following styling to the render view:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#E5E5E5",
  },
  header: {
    paddingTop: 50,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 16,
  },
  headerText: {
    fontSize: 28,
    fontWeight: "bold",
  },
  optionText: {
    fontSize: 20,
    color: "gray",
  },
  option: {
    justifyContent: "space-between",
    paddingHorizontal: 16,
    paddingVertical: 20,
    backgroundColor: "#FFFFFF",
    marginVertical: 10,
  },
  subOptionContainer: {
    alignItems: "center",
    flexDirection: "row",
    justifyContent: "space-between",
    paddingVertical: 16,
    backgroundColor: "#FFFFFF",
  },
});

Now, our app should look like this:

 

In the demo application above, Wi-Fi and location options are in the settings screen, while in the source code, we only have the Wi-Fi option implementation. I suggest implementing the Location option yourself to practice implementing the switch component.

Let’s take a look at the react-native-toggle-element package to explore more ways to customize the slide toggle.

Using react-native-toggle-element to build an advanced slide toggle

react-native-toggle-element is a third-party library that provides additional methods and properties for creating and customizing animated slide toggles in React Native. It has built-in options to customize the thumb button to use an icon, display text, or change colors when translating between two states.

In the rn-slide-toggle project that was created in the Getting started with React Native section, let’s ensure the file tree follows this structure:

…
├── assets
├── node_modules
├── redux-store
 │   ├── reducers.js
 │   └── store.js
├── src
 │   ├── BuiltInSlideToggle.js
 │   └── SlideToggle.js
 |── App.js
├── index.js
└── package.json

Once you’ve created the project files to mimic what we have above, in the package.json file set the main value to this ./index.js.


More great articles from LogRocket:


Then, install these packages:

yarn add react-native-toggle-element react-redux @reduxjs/toolkit

In this example, we’ll build a slide toggle functionality to switch between themes in the application. The application uses the redux-tool-kit to implement the theme update of choice and effect across the state of the app. Check out this guide on how to make Redux smarter with Redux Toolkit.

Inside reducers.js and store.js files, replace the code in there with the following:

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  mode: 'dark',
}

export const themeSlice = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    changeMode: (state, action) => {

      if (action.payload) {
        state.mode = 'light'
      } else {
        state.mode = 'dark'
      }
    },
  },
})
export const { changeMode } = themeSlice.actions 

export default themeSlice.reducer

Also, paste the following code into your store.js:

import themeReducer from './reducers';
import { configureStore } from '@reduxjs/toolkit'


export const store = configureStore({
    reducer: {
      theme: themeReducer,
    },
  })

export default store;

In your App.js file, update the code to this:

import SlideToggle from "./src/SlideToggle";
import { Provider } from 'react-redux';
import store from './redux-store/store';


export default function App() {

  return (
    <Provider store={store}>

    {/* The SlideToggle component would be instantiated from here*/}
       <SlideToggle/> 

       </Provider>
  );
}

Next, in the src/SlideToggle.js I will add the functionality for a slide toggle element by breaking each step into small bits.

So, right away, l will import the libraries to help build the features.

Inside the src/SlideToggle.js file, you can paste this code into there:

import React, { useState, useEffect } from "react"; // React core library and hooks

// View component
import { StyleSheet, View, Text } from "react-native";

// the third party library for slide toggle
import Toggle from "react-native-toggle-element";

import { StatusBar } from "expo-status-bar";

// Icon component, installed during expo setup
import { Fontisto } from "@expo/vector-icons"; 

// Global state storage to effect changes access the application
import { useSelector, useDispatch } from "react-redux";
import { changeMode } from "../redux-store/reducers"; 

In the src/SlideToggle.js I have created a function component to implement and render the slide toggle. Inside, I declare and assign values to toggleValue and mode state variables, dispatching the values for the current theme from the redux state via the dispatch and theme variables. We’ll also use the useEffect hook to listen to changes on the theme variable and re-render the UI.

The onToggle() is used as a trigger for the Toggle component to get the Boolean value for the current state of the slide toggle element.

Paste this code immediately below the import statements:

export default function SlideToggle() {
  // state variable within the component
  const [toggleValue, setToggleValue] = useState(false);


  const dispatch = useDispatch();
  const theme = useSelector((state) => state.theme);
  const [mode, setMode] = useState(theme.mode);

  const onToggle = (val) => {
    dispatch(changeMode(val)); // invoke the changeMode function and pass argument

    setToggleValue(val); // update the toggleValue state variable
  };

  useEffect(() => {
    setMode(theme.mode);
  }, [theme]);

  return (
    <>
      <View
        style={mode == "light" ? styles.container_light : styles.container_dark}
      >
        <Text style={mode == "light" ? styles.text_light : styles.text_dark}>
          We are on {theme.mode} mode!
        </Text>
        <Toggle
          value={toggleValue}
          onPress={(val) => onToggle(val)} // we access the val variable inside toggle component
          thumbActiveComponent={
            <Fontisto
              name="sun"
              color="black"
              width="40"
              height="40"
              fill={"#3BD2B5"}
            />
          }
          thumbInActiveComponent={
            <Fontisto
              name="night-clear"
              color="black"
              width="40"
              height="40"
              fill={"#03452C"}
            />
          }
          trackBar={{
            activeBackgroundColor: "#9ee3fb",
            inActiveBackgroundColor: "#3c4145",
            borderActiveColor: "#86c3d7",
            borderInActiveColor: "#1c1c1c",
            borderWidth: 5,
            width: 100,
          }}
        />
        <StatusBar style={mode === "light" ? "dark" : "light"} />
      </View>
    </>
  );
}

Consider the Toggle component in the return statement, where I am rendering the UI, which is used to actualize the slide toggle element for the app. For the Toggle element, I can pass in the onPress, value, thumbActiveComponent, thumbInActiveComponent, and trackBar props to the component to determine the current value of the slide toggle element, react to users’ actions, and display the appropriate UI.

Then, in the src/SlideToggle.js, paste the styles option after SlideToggle() :

const styles = StyleSheet.create({
  container_light: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },

  container_dark: {
    flex: 1,
    backgroundColor: "#121212",
    alignItems: "center",
    justifyContent: "center",
  },

  text_light: {
    marginBottom: 20,
    color: "#000",
  },

  text_dark: {
    marginBottom: 20,
    color: "#fff",
  },
});

Now, we will have a working application that switches between light and dark mode themes for an application:

Conclusion

In this article, we learned about slide toggles and how to build animated slide toggles in a React Native application. We also examined the core concept behind translating a component and explored existing libraries for creating slide toggles in React Native.

The complete code is available on GitHub. I hope you enjoyed this article, and be sure to leave a comment if you have any questions. Happy coding!

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

Paul Oloyede I’m a highly motivated mobile developer who focuses on quality, maintainability, and efficiency. I enjoy lecturing, speaking at conferences, and writing about technology and development. I find that I can be more effective by empowering others to do better.

3 Replies to “How to build an animated slide toggle in React…”

Leave a Reply