DevGe
DevGe

Reputation: 1459

How to implement the on change value on switch component in react native using native base & navigation 5

I have problem on changing the value of switch the default state is boolen: false, so when I toggle the switch to true, the state immediately will turn to false. I don't know where is the problem. I read some documents we both same properties via using onValueChange setting the value using the state.

I am confuse what the documentation tells

  1. It mentions that setstate can't call

When we define our button this way, the this variable in options is not the HomeScreen instance, so you can't call setState or any instance methods on it. This is pretty important because it's extremely common to want the buttons in your header to interact with the screen that the header belongs to. So, we will look how to do this next.

Any recommendation to fix this switches on the headerRight?

Goal: is when I toggle the switch button must change the value itself

State:

switchDriverOnlineValue: false,

Navigation Header:

      DriverHeader() {
    this.props.navigation.setOptions({
      headerLeft: () => <View style={{ flexDirection: "row", justifyContent: "flex-end", paddingLeft: 20 }}>
        <TouchableOpacity
          onPress={() => this.props.navigation.openDrawer()}
        >
          <Icon type="font-awesome" name="user-circle-o" size={30} color="white" />
        </TouchableOpacity>
      </View>,

      headerRight: () => <View style={{ flexDirection: "row", justifyContent: "flex-end" }}>
        <Text adjustsFontSizeToFit numberOfLines={2} style={{ color: '#FFFF', fontSize: 18, fontWeight: 'bold' }}>Online</Text>
        <Switch style={{ marginTop: 0 }} value={this.state.switchDriverOnlineValue} onValueChange={(value) => this.setState({ switchDriverOnlineValue: value })} />
      </View>,
    });
  }

Current Output:

current output

Logs:

Logs

Upvotes: 1

Views: 4313

Answers (1)

Karan Balodi
Karan Balodi

Reputation: 11

Here you have to toggle the previous value of the switchDriverOnlineValue state every time the value of the switch is changed so adding a ! to previous value will make it work.

<Switch style={{ marginTop: 0 }} value={this.state.switchDriverOnlineValue} onValueChange={(value) => this.setState({ switchDriverOnlineValue: !value })} />

Upvotes: 1

Related Questions