React Native - Switch - Mobile Application Development

Felicitations! You are standing in the right place! In this example, we initially set the Switch value to false and exhibit a Text with 'No'. When the value of Switch change to true by calling onValueChange the Text component is reset to 'Yes'.

Our screen will look like this −

Implementation

First, You must set up your local development environment. Follow the below link to set up your local environment.


After executing the commands mentioned in this link, a folder with a specified name is created with the following contents.



Import StyleSheet, Switch, View, and Text component in our project.

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

Declare State

The state is generally initialized in the constructor and then call setState when we want to change it.
state = {
married: false
};

Engender a Root View in render’s return block.

render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>Married</Text>
<Text style={styles.textStyle}>{this.state.married ?
'Yes' :'No'}</Text>
<Switch
value={this.state.married}
onValueChange ={(married)=>this.setState({married})}/>
</View>
);
}
}

Engender Style

const styles = StyleSheet.create ({
container: {
flex: 2,
alignItems: 'center',
justifyContent: 'center',
},
textStyle:{
margin: 26,
fontSize: 27,
fontWeight: 'bold',
textAlign: 'center',
color: 'purple'
}
})

Complete source code for App.js File

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

export default class App extends React.Component {
state = {
married: false
};

render() {
return (
<View style={styles.container}>
<Text style={styles.textStyle}>Married</Text>
<Text style={styles.textStyle}>{this.state.married ? 'Yes' :'No'}
                         </Text>  
<Switch
value={this.state.married}
onValueChange ={(married)=>this.setState({married})}/>
</View>
);
}
}
const styles = StyleSheet.create ({
container: {
flex: 2,
alignItems: 'center',
justifyContent: 'center',
},
textStyle:{
margin: 26,
fontSize: 27,
fontWeight: 'bold',
textAlign: 'center',
color: 'purple'
}
})

Run

sibinmuhammed@ladmin-H310M-S2:~$ react-native start
sibinmuhammed@ladmin-H310M-S2:~/knf-reactnative/KnowledgeFactoryDemo$ react-native run-android

More...


Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete