Search code examples
react-nativetouchableopacitytouchablehighlight

TouchableOpacity and TouchableHighlight always disabled


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>

Solution

  • 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})}}