DEV Community

Cover image for How To Hide and Show Password In React JS
Udemezue John
Udemezue John

Posted on

How To Hide and Show Password In React JS

Introduction.

In most modern web applications, password fields often come with a small “eye” icon that lets users toggle between hiding or showing the password they are typing.

It’s a simple but essential feature that enhances user experience by offering both security and convenience. If you’ve ever wondered how to implement this in a React app, I’ve got you covered.

In this guide, I'll walk through the process of adding a “show/hide password” functionality using React.js.

How Do I Hide and Show Password In React JS?

When building a form in React, one common feature that enhances the user experience is the ability to toggle between showing and hiding a password field.

Password fields are typically masked for security reasons, but providing users with the option to reveal the password can be helpful to avoid mistakes while typing.

Let’s dive into how to implement this functionality in a React application, step by step.

1. Set Up the Project.

First, ensure you have React set up in your environment. If you don’t already have a project, you can create one quickly using create-react-app.

If you're starting from scratch, open your terminal and run the following:

npx create-react-app password-toggle
cd password-toggle
npm start
Enter fullscreen mode Exit fullscreen mode

This will initialize a new React project and open the development server in your browser.

2. Basic Password Input Field.

Let’s start by creating a basic password input field in React. Open the src/App.js file and add a simple form with a password field:

import React from 'react';

function App() {
  return (
    <div className="App">
      <form>
        <label>Password:</label>
        <input type="password" placeholder="Enter your password" />
      </form>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

At this stage, it's just a regular password field where the characters are masked by default.

3. Implementing the Toggle Logic.

Now, let's add the functionality to toggle between hiding and showing the password. To do this, I need to:

Keep track of the current state (whether the password is hidden or visible).

Toggle the type attribute of the password input between "password" and "text".

I'll use the useState hook to handle this:

import React, { useState } from 'react';

function App() {
  const [showPassword, setShowPassword] = useState(false);

  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  return (
    <div className="App">
      <form>
        <label>Password:</label>
        <input 
          type={showPassword ? "text" : "password"} 
          placeholder="Enter your password" 
        />
        <button 
          type="button" 
          onClick={togglePasswordVisibility}
        >
          {showPassword ? "Hide" : "Show"}
        </button>
      </form>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

4. Breaking Down the Code.

useState(false): I’m initializing a state variable showPassword with a default value of false.

This means the password will be hidden initially.

  • togglePasswordVisibility(): This function flips the value of showPassword between true and false, which in turn updates the type of the input field.
  • : This is the key. The type of the input switches between "password" (masked) and "text" (visible) based on the state.

The button label changes dynamically between "Show" and "Hide" based on the value of showPassword.

5. Styling the Button.

Right now, the button is functional but not visually appealing. Here’s how you can style it using some basic CSS. First, add a class to the button:

<button 
  type="button" 
  className="toggle-password"
  onClick={togglePasswordVisibility}
>
  {showPassword ? "Hide" : "Show"}
</button>

Enter fullscreen mode Exit fullscreen mode

Then, in the src/App.css file, add the following styles:

form {
  margin: 20px;
}

input {
  padding: 10px;
  font-size: 16px;
  margin-right: 10px;
}

.toggle-password {
  padding: 10px;
  background-color: #007BFF;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 16px;
  border-radius: 5px;
}

.toggle-password:hover {
  background-color: #0056b3;
}

Enter fullscreen mode Exit fullscreen mode

This makes the button look more modern and interactive.

6. Adding Icons Instead of Text.

If you want a more intuitive design, you could use icons (like an eye icon) instead of plain text for the button. This can be achieved using Font Awesome or any other icon library.

First, install Font Awesome by running:

npm install @fortawesome/fontawesome-free
Enter fullscreen mode Exit fullscreen mode

Next, import the necessary CSS in src/index.js:

import '@fortawesome/fontawesome-free/css/all.min.css';
Enter fullscreen mode Exit fullscreen mode

Then, update the button in App.js to use icons:

<button 
  type="button" 
  className="toggle-password"
  onClick={togglePasswordVisibility}
>
  <i className={showPassword ? "fas fa-eye-slash" : "fas fa-eye"}></i>
</button>
Enter fullscreen mode Exit fullscreen mode

With these changes, the button will now show an eye or an eye-slash icon depending on the state.

  1. Enhancements and Considerations.

Accessibility: Always ensure your app is accessible to everyone. You can add aria-label attributes to the button to describe its action to screen readers. For instance:

<button 
  type="button" 
  className="toggle-password"
  aria-label={showPassword ? "Hide password" : "Show password"}
  onClick={togglePasswordVisibility}
>
  <i className={showPassword ? "fas fa-eye-slash" : "fas fa-eye"}></i>
</button>

Enter fullscreen mode Exit fullscreen mode

Security Tip: While showing the password can improve usability, it's essential to remind users to use strong, secure passwords and avoid revealing them in insecure environments.

Make sure your app doesn’t compromise security while improving user experience.

8. Testing Your Application.

Finally, to ensure your password toggle works across different environments and edge cases:

Test the input field on both desktop and mobile devices.

Confirm that the button properly toggles the password visibility and that the input field remains usable.

This solution should work seamlessly across modern browsers and provides an enhanced experience for users filling out forms on your site.

Conclusion.

Toggling password visibility is a small yet effective feature in improving user experience.

In React, it's straightforward to implement using state and a simple toggle button.

Adding features like this one keeps your applications user-friendly without over-complicating the code.

With just a few lines of code, you’ve enhanced the usability of your app and made it easier for users to manage passwords more effectively.

Top comments (0)