react native hidden text on textinput

How to hide text on TextInput using React Native?

React Native is a popular framework used for creating mobile applications. Often, we need to hide the text input from the users, especially while entering sensitive data such as passwords. In this PAA, we will discuss how to hide text on TextInput using React Native.

Method 1: Using 'secureTextEntry' property

The easiest method to hide text on TextInput is by using the 'secureTextEntry' property. When this property is set to 'true', the entered text will be masked, and the user will not be able to see what they are typing.


<TextInput secureTextEntry={true} />

The above code will create a TextInput where the entered text will be masked. You can also set the 'secureTextEntry' property dynamically based on certain conditions.

Method 2: Using 'passwordRules' property (iOS only)

In iOS 12 and later, there is a new property called 'passwordRules', which allows us to customize the password policy for a TextInput. We can use this property to mask the entered text.


<TextInput passwordRules={ {allowPassword: false} } />

The above code will create a TextInput where the entered text will be masked. We can also customize the password policy based on our requirements.

Method 3: Using 'onKeyPress' event

If you want to show some characters while typing and mask the rest, you can use the 'onKeyPress' event. In this method, we will listen to every key press and update the state with the entered text.


import React, {useState} from 'react';
import {TextInput} from 'react-native';

const HiddenTextInput = () => {
  const [text, setText] = useState('');
  const onChangeText = (inputText) => {
    let hiddenText = '';
    for (let i = 0; i < inputText.length; i++) {
      hiddenText += '•'; // replace with your desired character
    }
    setText(hiddenText);
  };
  return (
    <TextInput value={text} onChangeText={onChangeText} />
  );
};

The above code will create a TextInput where the entered text will be masked with the '•' character. You can replace it with your desired character.

Conclusion:

Hiding text on TextInput in React Native is simple and can be achieved using various methods. You can choose the method based on your requirements and preferences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe