Open In App

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: 

Now let’s start with the implementation:



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




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"}}>
        GeeksforGeeks
      </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


Article Tags :