Home » React JS

How to use the Switch Component in React Native App?

React Native | Switch Component: Here, we are going to learn how to use the Switch Component in React Native App?
Submitted by Godwill Tetah, on February 10, 2020

Hi! Guys! It's Sunday and today we are going to talk about the default switch component in react-native.

As we all know from normal English, a switch provides a simple system to toggle ON/OFF.

on off button

The image above is called a switch which we see on our android mobile phones.

To add the picker component in your app is not complex but just to follow the rules and syntax.

Below is an example:

In your App.js File, type the following,

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

export default class App extends React.Component {
  state = {  
        switchStatus: false  
    };  
  render() {
    return (
      <View style={styles.container}>
        <Text> Switch Example! </Text>
        <Text style={styles.textStyle}>{this.state.switchStatus ? 'on' :'off'}</Text>  
                <Switch  
                    value={this.state.switchStatus}  
                    onValueChange ={(switchStatus)=>this.setState({switchStatus})}/>  
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'skyblue',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Output

How to use the Switch Component in React Native App?

From the code above, the switch function is invoked using the switch self-closing tag. In this example, the switch component has the value and the valueChange attribute.
The value attribute is used to simply set the default value of the switch when the app is first opened while the valueChange attribute carries the event handler when the value of the switch is changed.

In this case, the event handler simply changes the state.

Take note of the fact that the component was first of all imported before use.

Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question. God Bless You!



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.