React Native Tutorial
Core Concepts
Components and APIs
React Native Useful Resources
Selected Reading
Core Concepts
- React Native - Running Android
- React Native - Running IOS
- React Native - Router
- React Native - Debugging
- React Native - Animations
- React Native - Buttons
- React Native - HTTP
- React Native - Images
- React Native - ScrollView
- React Native - Text Input
- React Native - ListView
- React Native - Flexbox
- React Native - Styling
- React Native - Props
- React Native - State
- React Native - App
- React Native - Environment Setup
- React Native - Overview
Components and APIs
- React Native - AsyncStorage
- React Native - Geolocation
- React Native - Alert
- React Native - Text
- React Native - Switch
- React Native - Status Bar
- React Native - Picker
- React Native - ActivityIndicator
- React Native - Modal
- React Native - WebView
- React Native - View
React Native Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
React Native - Switch
React Native - Switch
In this chapter, we will explain the Switch component in a couple of steps.
Step 1: Create File
We will use the HomeContainer component for logic, but we need to create the presentational component.
Let us now create a new file: SwitchExample.js.
Step 2: Logic
We are passing value from the state and functions for toggpng switch items to SwitchExample component. Toggle functions will be used for updating the state.
App.js
import React, { Component } from react import { View } from react-native import SwitchExample from ./switch_example.js export default class HomeContainer extends Component { constructor() { super(); this.state = { switch1Value: false, } } toggleSwitch1 = (value) => { this.setState({switch1Value: value}) console.log( Switch 1 is: + value) } render() { return ( <View> <SwitchExample toggleSwitch1 = {this.toggleSwitch1} switch1Value = {this.state.switch1Value}/> </View> ); } }
Step 3: Presentation
Switch component takes two props. The onValueChange prop will trigger our toggle functions after a user presses the switch. The value prop is bound to the state of the HomeContainer component.
switch_example.js
import React, { Component } from react import { View, Switch, StyleSheet } from react-native export default SwitchExample = (props) => { return ( <View style = {styles.container}> <Switch onValueChange = {props.toggleSwitch1} value = {props.switch1Value}/> </View> ) } const styles = StyleSheet.create ({ container: { flex: 1, apgnItems: center , marginTop: 100 } })
If we press the switch, the state will be updated. You can check values in the console.
Output
![React Native Switch](/react_native/images/react_native_switch.jpg)