1

I am trying to disable a TouchableOpacity element when username/password fields are not filled. It does not work. It is always in a disabled state.

I printed the condition !this.state.username || !this.state.password to console and it is only false when both are filled which is the desired result but the disabled property of TouchableOpacity does not seem to reflect the value in this condition. Below is a snippet of my code:

can anyone suggest a solution to this problem?

<ScrollView style={styles.content}>
      <View style={[styles.container, styles.content]}>
        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={emailicon}/>
          <TextInput style={[styles.inputs]}
              ref={`username`}
              placeholder="Email"
              keyboardType="email-address"
              underlineColorAndroid='transparent'
              onChangeText={(text) => {this.state.username = text}}
              required={true}
          />
        </View>

        <View style={styles.inputContainer}>
          <Image style={styles.inputIcon} source={keyicon}/>
          <TextInput
              style={styles.inputs}
              ref={`password`}
              placeholder="Password"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(text) => {this.state.password = text}}
              required={true}
          />
        </View>

        <TouchableOpacity style={[styles.buttonContainer, styles.loginButton]}
                            onPress={() => { console.log(!this.state.username || !this.state.password) }} disabled={!this.state.username || !this.state.password}>
          <Text style={styles.loginText}>Login</Text>
        </TouchableOpacity>
Paras Korat
  • 2,011
  • 2
  • 18
  • 36
F. K.
  • 694
  • 3
  • 9
  • 23

1 Answers1

1

Try to use setState instead of assign value this state in onChangeText.

Just replace this line in both textInput

onChangeText={(text) => {this.setState({username:text})}}

and

onChangeText={(text) => {this.setState({password:text})}}
Paras Korat
  • 2,011
  • 2
  • 18
  • 36
  • @"paras Korat", thank you so much. That fixed it. Why does it make a difference whether you explicitly set the state value or use setState? – F. K. Apr 06 '19 at 14:14
  • 1
    explicitly set value won't render your component while setState does. – Paras Korat Apr 06 '19 at 14:20