React Native Tutorial on 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 toggling 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,
      alignitems: 'center',
      margintop: 100
   }
})

if we press the switch, the state will be updated. you can check values in the console.

output

react native switch