react-nativetouchablehighlight

React Native chagne image source on button click


Hi I am trying to change image on a button click but cant seem to get the image to change. Here is my code.

constructor(){
   super()
   this.state = {
      autologin_active: true
   }
}

toggleAutoLogin(){
   this.state.autologin_active = this.state.autologin_active ? false : true;
}


<TouchableHighlight onPress={() => this.toggleAutoLogin()} style={styles.registerButton} underlayColor='#99d9f4'>
  <View style={styles.detailBoxTick}>
    <Image style={styles.imageTickStyle} source={this.state.autologin_active ? Images.rememberTickImg : Images.rememberUnTickImg} />
    <Text style={styles.tickBoxText}>
      Auto Login
    </Text>
  </View>          
</TouchableHighlight>

can some one please help. Not sure what I am doing wrong. Have checked with alert that the state is changing on click. Thanks in advance


Solution

  • If I got you correctly, in toggleAutoLogin(), you are updating your state with this.state.autologin_active = ..... which is updating the state but preventing the re-render so that you can't see the image changing.

    You need to update the state with setState({}) in order to re-render the component (Image).

    Your code for toggleAutoLogin() would be:

    this.setState({ autologin_active: this.state.autologin_active ? false : true})