React Native Switch API
In this article, We are going to see how to use Switch in react-native. For this, we are going to use the Switch component. It is a controlled component that requires a callback function that updates the props to show the user’s action.
Syntax :
<Switch // props trackColor={} thumbColor={} value={} />
Props in Switch:
- Disabled: If its value is true then the user won’t able to toggle the switch.
- ios_backgroundColor: It is only available for IOS. It is basically for the custom background color in IOS.
- onChange: It is Invoked when a user tries to change the value of the switch. It receives the change event as an argument.
- onValueChange: It also Invoked when a user tries to change the value of the switch. But it receives changed value as an argument instead of the event.
- thumbColor: It is basically the color of the foreground switch grip.
- trackColor: It is basically the color of the switch track.
- value: It is the value of the switch. By default, it is false.
Now let’s start with the implementation:
-
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
-
Step 2: Now create a project by the following command.
expo init myapp
-
Step 3: Now go into your project folder i.e. myapp
cd myapp
Project Structure:
Example: Now let’s implement the Switch. Here we created a Switch and when someone toggles the switch the color of the switch and text will change.
App.js
Javascript
import React , {useState} from 'react' ; import {StyleSheet, Text, View, Switch } from 'react-native' ; export default function App() { const [Enable , setEnable] = useState( false ); // Toggle function const toggle = (state)=>{ setEnable(state); } return ( <View style={styles.container}> <Text style={{color : Enable ? "red" : "green" }}> w3wiki </Text> <Switch trackColor={{ false : "#43f746" , true : "#63dff2" }} thumbColor={Enable ? "#faf68c" : "#e243f7" } onValueChange={toggle} value={Enable} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center' , justifyContent: 'center' , }, }); |
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.
Reference: https://reactnative.dev/docs/switch