React Native Switch  component is for showing the boolean value or to select from one out of two options.

A Switch is a controlled component that contains a callback onValueChange that updates the value prop. If the value prop is not updated, the component will continue to render the supplied value prop instead of the expected result of any user actions

 

Syntax

<Switch onValueChange = {handlerHere} value = {Pre decided value if any}/>

 

Example:

//This is an example code to understand Switch// 

import React from 'react';

//import react in our code. 

import { Switch, Text, View, StyleSheet } from 'react-native';

//import all the components we are going to use. 

export default class SwitchExample extends React.Component {

  //Initial state false for the switch. You can change it to true just to see.

  state = {switchValue:false}

  toggleSwitch = (value) => {

      //onValueChange of the switch this function will be called

      this.setState({switchValue: value})

      //state changes according to switch

      //which will result in re-render the text

   }

  render() {

    return (

      <View style={styles.container}>

         <View style={styles.header}>

          <Text>Switch Example</Text>

        </View>

        <View style={styles.body}>

        <Text>{this.state.switchValue?'Switch is ON':'Switch is OFF'}</Text>

       

        <Switch

          style={{marginTop:30,color:'green'}}

           trackColor={{true: 'green', false: 'red'}}

           thumbColor={{true:'#7ab8e1',false:'pink'}}

          onValueChange = {this.toggleSwitch}

          value = {this.state.switchValue}/>

          </View>

      </View>

    );  

  } 

}

const styles = StyleSheet.create({

    container: {

        backgroundColor: '#FAFAFA',

        flex: 1,

      },

      header: {

        alignItems: 'center',

        padding: 10,

        backgroundColor: 'cyan',

      },

      body: {

        backgroundColor: 'grey',

        padding: 16,

        flex: 1,

      },

});

 

 

Output

Switch Component

How to change the color of Switch in React Native?

 <Switch 
      trackColor={{true: 'red', false: 'grey'}}
      onValueChange={this.toggleSwitch}
      value={true}/>

 


Subscribe For Daily Updates