React Native

React Native – Switch

This is a controlled component that requires an onValueChange callback that updates the value prop in order for the component to reflect user actions. 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.

PropsDescription
disabledIt is a Boolean property, if it is set to true then it cannot be toggled to switch. Its default value is false.
trackColorIt is used to customize the color for switch track.
ios_backgroundColorIt set the custom background color in iOS. The background can be visible either when the switch value is disabled or when the switch is false.
onValueChangeIt invoked when the switch value is changed.
testIDIt is used to locate this view in end-to-end tests.
thumbColorIt colors the foreground switch grip. When it is set to iOS, the switch grip will lose its drop shadow.
tintColorIt sets the border color on iOS and background color on Android when the switch is turned off. This property is deprecated; use trackColor at the place of it.
valueIt is the value of switch. When it is set to true, it turns on. The default value is false.
import { Switch} from 'react-native'
import React from 'react';
import { Switch, Text, View, StyleSheet } from 'react-native';
export default class App 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}>
        {/*Text to show the text according to switch condition*/}
        <Text>{this.state.switchValue?'Switch is ON':'Switch is OFF'}</Text>
        {/*Switch with value set in constructor*/}
        {/*onValueChange will be triggered after switch condition changes*/}
        <Switch
          style={{marginTop:30}}
          onValueChange = {this.toggleSwitch}
          value = {this.state.switchValue}/>
      </View>
    );  
  } 
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  }
});

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Back to top button