react native-tutorial

React Native Switch

A Boolean control component called React Native Switch sets its value to either true or false. Its value prop is updated by the onValueChange callback method. The Switch component continues to supply the value prop if the value prop is not altered, rather than the anticipated outcome of any user actions.

Properties of Switch

  • disabled: It is a Boolean property that cannot be toggled to switch if it is set to true. False is its default value.
  • trackColor: It is used to alter the switch track’s colour.
  • ios_backgroundColor: It changed iOS’s user-defined backdrop colour. When the switch value is disabled or false, the background can be seen in any case.
  • onValueChange: When the switch value changes, it is invoked.
  • testID: In end-to-end tests, it is used to identify this perspective.
  • thumbColor: The switch grip in the foreground is coloured. The switch grip will no longer have a drop shadow when it is set to iOS.
  • tintColor: When the switch is off, it sets the background colour on Android and the border colour on iOS. Use trackColor instead of this deprecated property.
  • value: It is the switch’s value. It activates when set to true. False is the default setting.

Creating the project

We will be making use of Expo in order to bootstrap our project. If you haven’t installed Expo earlier then run the following command to install it:

npm install --global expo-cli

Now create a new Expo project using the following command. While creating the project, it would ask you to select a template. Choose “blank” template.

expo init react-native-switch

Once the installation is completed run npm start and run the application in your device or on Android Studio Emulator or iOS Emulator.

The switch component

Update your App.js to the following code:

App.js

import { StatusBar } from "expo-status-bar"
import React, { useState } from "react"
import { StyleSheet, Text, View, Switch } from "react-native"

export default function App() {
  const [enabled, setEnabled] = useState(false)

  const toggleSwitch = () => {
    setEnabled(oldValue => !oldValue)
  }

  return (
    <View style={styles.container}>
      <Switch onValueChange={toggleSwitch} value={enabled} />
      <StatusBar style="auto" />
    </View>
  )
}

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


Here we are calling toggleSwitch whenever the switch is pressed and in toggleSwitch function, we are setting the state to the negated value of the previous state. That is if the previous value is false then change it to true and vice versa.

If you run the app in Android/iOS and enable the switch this is how it would look:

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *