日本語

“React: How to Toggle Password Visibility (Show/Hide)”

​​React​Accessibility,HTML,Playwright,TypeScript

You can show and hide a password by switching the input's type between "password" and "text". In React, you keep "is it visible?" in one state value and write type={visible ? 'text' : 'password'}. The entered value is not lost when you switch.

The toggle button needs more care. In a test environment, I checked what happens when you forget type="button" (the form gets submitted), how to combine the accessible name with aria-pressed, and where focus goes after the button is pressed.

Note

The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx with tsc, converted it with esbuild, and drove Chromium with Playwright. I did not test screen reader announcements, soft keyboards on smartphones, Firefox or Safari, or autofill by browsers and password managers. I confirmed the names that screen readers use by exporting the accessibility tree with Playwright.

Typing "neko-Pass1" into the password field shows it as black dots. Clicking the eye-icon button once reveals the text, and clicking it again returns it to dots
Typing a password and clicking the eye-icon button twice. The type display below turns pink only at the moment it changes. The cursor, click ripple, and the type and click-count displays were added as overlays for the GIF. The labels in the image are in Japanese.

A component that switches type with state

PasswordInput receives the field's name for form submission, its label, and an autoComplete value. The label and the input are linked by an ID created with React's useId.

tsx
import { useId, useState } from 'react';

type Props = {
  name: string;
  label: string;
  autoComplete: 'current-password' | 'new-password';
};

export function PasswordInput({ name, label, autoComplete }: Props) {
  const id = useId();
  const [visible, setVisible] = useState(false);

  return (
    <div className="password-field">
      <label htmlFor={id}>{label}</label>
      <div className="password-row">
        <input
          id={id}
          name={name}
          type={visible ? 'text' : 'password'}
          autoComplete={autoComplete}
          autoCapitalize="off"
          spellCheck={false}
        />
        <button
          type="button"
          aria-label="パスワードを表示"
          aria-pressed={visible}
          aria-controls={id}
          onClick={() => setVisible((v) => !v)}
        >
          {visible ? <EyeOffIcon /> : <EyeIcon />}
        </button>
      </div>
    </div>
  );
}

EyeIcon and EyeOffIcon are simple SVGs: one draws an eye, the other draws the same eye with a diagonal line over it. Both have aria-hidden="true" so screen readers skip them (the code is omitted here).

The input gets neither value nor onChange. The browser keeps the value, and React changes only the type. In the test, I typed "neko-Pass1" and clicked the button twice. type changed from password to text and then back to password, and the value stayed "neko-Pass1" the whole time.

autoComplete and input aids while the text is visible

For a login field, pass current-password as autoComplete. For a registration or password-change field where a new password is entered, pass new-password. According to MDN's explanation of input type="password", both values give browsers and password managers hints for autofill. While type was text, the autocomplete attribute stayed current-password.

autoCapitalize="off" and spellCheck={false} are there for when the text is visible. MDN's explanation of autocapitalize says that automatic capitalization does not happen in type="password" fields. Once the type is text, that assumption no longer holds. So I set off to keep the first letter from being capitalized on a smartphone's soft keyboard. Setting spellcheck to false excludes the field from spell checking. The same MDN page notes that spell checking may send the entered content to an external service, so consider false for fields that hold sensitive information. I did not verify either setting's effect in this test environment.

Give the button type="button"

Inside a form, a button with no type acts as a submit button (MDN's explanation of the button type attribute). To compare, I tested a version of the toggle button without type="button". The submit handler counted how many times it ran.

Toggle button Submit count after two clicks on the button
With type="button" 0
Without type 2

Without type, the form was submitted on every press, both when showing and when hiding. On a login form, just checking the password would start the login process.

Even with type="button", pressing Enter in the password field still submitted the form. Pressing Enter while the text was visible (type was text) also submitted it. In both cases, the submitted values were as follows. Even when type is text, the value is sent under the same name.

text
{"email":"neko@example.com","password":"neko-Pass1"}

Keep the accessible name, and use aria-pressed for state

The button contains only an icon, so I gave it an aria-label with the Japanese text meaning "Show password". The visibility state is conveyed with aria-pressed, not with the name. When I exported the accessibility tree with Playwright, the button looked like this:

text
クリックする前:
- button "パスワードを表示"
1回クリックしたあと:
- button "パスワードを表示" [pressed]

The name stays the same, and only the pressed state changes. MDN's explanation of aria-pressed says not to change the name of a toggle button to match its state, and that if you want the name to change, you should not use aria-pressed. The W3C ARIA Authoring Practices Guide button pattern also says that keeping the name constant is important, and that if the name changes, aria-pressed is not needed.

There is another option: write visible text on the button, "Show password" and "Hide password" in the Japanese UI, and swap the text on each press. In that case, you do not add aria-pressed. In the version I tested, the button name changed like this:

text
クリックする前:
- button "パスワードを表示する"
1回クリックしたあと:
- button "パスワードを隠す"

With either approach, the name tells the user what pressing the button will do. Swapping "show" and "hide" as the name while also adding aria-pressed is the pattern that both of the references above advise against.

After pressing the button, focus moves to the button

In Chromium 153 in the test environment, clicking this component's button with the mouse moved focus from the password field to the button. With the keyboard, Tab moved focus from the password field to the button, and both Space and Enter toggled it.

Action type Where focus is
Tab from the password field password Toggle button
Space text Toggle button
Enter password Toggle button

When returning to the password field to keep typing, the result depended on how you returned. After clicking the button, if you clicked in the middle of the field (to the right of the typed characters), the cursor was placed at the end. Typing "X" then produced "neko-Pass1X". On the other hand, if you returned to the field with Shift+Tab, all of the entered characters were selected. Typing "X" then left only "X" as the value.

Warning

If you toggle with the button, return to the field with Shift+Tab, and then type, the password entered so far is replaced. (Tested in Chromium 153 in the test environment, after switching with a mouse click.)

Keeping focus in the field moves the cursor to the start

If you want focus to stay in the field even when you press the button with the mouse, you can call e.preventDefault() in the button's onMouseDown. I tested this approach as well.

tsx
<button
  type="button"
  aria-label="パスワードを表示"
  aria-pressed={visible}
  aria-controls={id}
  onMouseDown={(e) => e.preventDefault()}
  onClick={() => setVisible((v) => !v)}
>

Focus stayed in the field after the click, but the cursor jumped to the start. I placed the cursor after "neko" (after the fourth character), clicked the button, and typed "X". The results were as follows.

Action Cursor position Value
Place cursor after the fourth character 4 neko-Pass1
Click the button 0 neko-Pass1
Type "X" 1 Xneko-Pass1

You meant to continue typing, but the character landed at the start of the password. I ran the same steps with a plain HTML input and button, without React, and the cursor also jumped to the start. So I believe this comes from browser behavior, not from React. In the version where focus moved to the button, the cursor stayed at position 4 while the field did not have focus. This article's PasswordInput does not keep focus in the field this way.

​Posted by 86