Password TextInput in React-Native

Swair AQ
3 min readMay 8, 2020

--

how to make secure password TextInput

We'll cover:

  • Make secure TextInput from Basic RN TextInput component
  • Add a eye icon at corner to see password and toggle.

Let's get coding, make a basic fancy TextInput from here to switch styles on focus and onBlur of TextInput. i.e. if user enters TextInput we'll change styles and make it look more active and if user leaves we can make it look more greyed out. Check it out.

Now we'll just converse our custom component to make it a password field.

<TextInputsetFocus={focus}onChangeText={text => props.onChangeText(text)}onFocus={() => setFocus(true)}onBlur={() => setFocus(false)}secureTextEntry={secure} //we just added thisstyle={styles.textInput}placeholder={props.placeholder} />

that's what we have so far from previous article now to mutate it first we need a state to toggle our secure mode on icon click:

const [secure, setSecure] = React.useState(props.secure);

add it to top of your function component.

And later after your TextInput add:


{
props.secure &&<Icon style={{ paddingRight: 15, }}name={secure ? "eye" : 'eye-slash'}size={20} color='gray' onPress={() => setSecure(!secure)} />}

We'll check if parent want this TextInput to be secure i.e. password field, and if prop contains true we'll show an icon to the right side of our main view right after TextInput to make it look like a part of textInput.

Now, to toggle onClick of eye Icon we want to see password and change icon too, to change icon we can give icon name based on our current state if state contains true than we'll show secure icon and if it's false we'll show non-secure icon.

On Click of icon we will toggle our state to opposite of current and for that we simply wrote setSecure(!secure). i.e. opposite of current state.

{!props.secure &&<View style={{ paddingRight: 15, width: 30, height: 10 }} />} 

to further stable our design we added an empty view which took enough space as icon did, if TextInput is called as nonsecure object i.e. normal TextInput we want our TextInputs to look visibly same.

And that's all now we can call our component in our screen by passing basic props:

<TextInputonChangeText={(value) => console.log(value)}placeholder="Password"secure={true} //we pass secure component to identify its passwordstyle={{ marginTop: 20 }} //give custom styles/>
Hidden Password
Visible Password

That's all folks, if you like the article don't forget it to drop a clap and if you don't please tell me how can I improve.

--

--

Swair AQ
Swair AQ

Written by Swair AQ

Swair Arshad, React Native developer with a core in iOS. Software enthusiast focused on growth and helping developers become better together.

Responses (2)