Search code examples
reactjsreact-nativeuiswitch

How to add a function when deactivating Switch Button on ReactNative?


I manage to add a function to Switch button on my component like so :

            <Switch
                onValueChange={(value)=>this.onPressIcon(_key)}
                style={{marginBottom: 10}}
                value={this.state.trueSwitchIsOn}
            />

It triggers the function onPressIcon which increments a value by 1. Now, how can it triggers another function when the Switch button is deactivated ? (so the value will decrement)


Solution

  • the value will return true when the switch is active and false otherwise. So you can use that to fire two different functions depending on the value. So something like the following:

    onPressIcon = (value) => {
      // if the switch is activated, execute increment function
      if (value) {
        this.incrementSomething();
    
        // ... rest of code
    
      } else {
        // switch is deactivated, execute other function
        this.otherFunction();
    
        // ... rest of code
    
      }
    }
    
    // render 
    render () {
      return(
    
        //... rest of code
    
        <Switch
          onValueChange={(value) => this.onPressIcon(value)}
          style={{marginBottom: 10}}
          value={this.state.trueSwitchIsOn}
        />
      );
    }