How to achieve React Native Password Show Hide without side effect

Viewed 5253

I want to do a password box that:

  • show/hide password and the TextInput won't lose focus.
  • The keyboard type won't change
  • when change password box state without focus, won't auto focus.

My codes are something like following:

      <View style={styles.container}>
        <TextInput
          style={styles.textInput}
          value={text}
          onChangeText={text => this.setState({ text })}
          secureTextEntry={secureTextEntry}
          underlineColorAndroid="transparent"
        />
        <TouchableWithoutFeedback
          onPress={() => (showing ? this.hide() : this.show())}
        >
          <Image source={this.image} />
        </TouchableWithoutFeedback>
      </View>

But this will make focus lose when I click change image. So how can I get the aim?

2 Answers

I think you can autofocus again on the password input using "ref" prop.

Add the ref prop in your TextInput:

  <View style={styles.container}>
    <TextInput
      ref={c => {this.passwordTextInput= c}} //add Reference Prop
      style={styles.textInput}
      value={text}
      onChangeText={text => this.setState({ text })}
      secureTextEntry={secureTextEntry}
      underlineColorAndroid="transparent"
    />

and then call

 this.passwordTextInput.focus();

in both this.hide() and this.show() functions after updating state.

Related