DEV Community

Tim Bogdanov
Tim Bogdanov

Posted on

Show & Hide Passwords with React

Understanding React useState Hook

To understand the work around of showing and hiding password string inside of an input field we must first understand the useState hook.

Elements state inside of basic React apps is managed by something called a useState hook. Bodies of data like javascript objects, arrays, string, booleans, etc. can be stored inside of a useState variable.

For example:

const [showPassword, setShowPassword] = useState(false)
Enter fullscreen mode Exit fullscreen mode

In the example above we assign showPassword to false by default. After that comes the setter variable. We can use that whenever someone clicks on a button/icon to reveal the password.

For example

const [showPassword, setShowPassword] = useState(false)

const togglePass = (e) => {
  e.preventDefault() // Important! If you don't include this your page will refresh

  setShowPassword(!showPassword)
}

return (
<>
  <form>
    <input type='password' />
    <button onClick={togglePass}>Toggle Password</button>
  </form>
</>
)
Enter fullscreen mode Exit fullscreen mode

As you can see from the example above, we have a function that set the showPassword to the opposite of what it currently is -- if its true set it to false, if its false set it to true.

After that we have a simple form field with one input and a button. The onClick on the button is set the the togglePass function. So whenever you click on the button it will perform the simple task of switching it from true to false and vice-versa.

This is where the magic happens. As you probably noticed, we hard coded the type on input in the code above. Lets fix that.

const [showPassword, setShowPassword] = useState(false)

const togglePass = (e) => {
  e.preventDefault() // Important! If you don't include this your page will refresh

  setShowPassword(!showPassword)
}

return (
<>
  <form>
    <input type={showPassword ? 'password' : 'text'} />
    <button onClick={togglePass}>Toggle Password</button>
  </form>
</>
)
Enter fullscreen mode Exit fullscreen mode

Using a ternary operation we can set a conditional statment. In plain English it reads as follows:

If showPassword is true, then set the input type to password. If it is not true (false), then set the input type to text.

With these few lines of code we can easily create a show and hide for a password form field in React!

Top comments (1)

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Simple post yet does one thing well :)