0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】パスワード入力画面で表示と非表示を切り替えるメモ

Posted at

Reactでパスワードの表示と非表示を切り替える

実現したいこと

目のアイコンをクリックすることでパスワードの表示を切り替える

  • 非表示
    スクリーンショット 2022-08-19 8.00.35.png
  • 表示
    スクリーンショット 2022-08-19 8.00.50.png

実行環境

  • macOS Monterey
  • React 18.1.0

手順

  1. パスワードの変数をuseState()で宣言
  2. 表示 or 非表示の判定用変数をuseState()で宣言
  3. 目のアイコンと判定用変数の紐付け
  4. onClick()で表示・非表示を切り替える

コード

Password.js
import React, { useEffect, useState } from "react";
import VisibilityIcon from "@mui/icons-material/Visibility";
import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";

function Password(){
    const [password, setPassword] = useState("");
    const [passwordType, setPasswordType] = useState("password");

    return (
        // 入力フォーム
        <input 
            value={password}
            type={passwordType}
            placeholder={"Type New Password"}
            autoComplete="new-password"
            required
            onChange={(e) => {
              setPassword(e.target.value);
            }}
            className="Password"
         />
        // 非表示
        {passwordType === "password" && (
            <VisibilityOffIcon
              onClick={() => setPasswordType("text")}
              className="Password__visual"
            />
        )}
        // 表示
        {passwordType === "text" && (
            <VisibilityIcon
              onClick={() => setPasswordType("password")}
              className="Password__visual"
            />
        )}
    );
}

ポイント

inputタグのtypeでパスワードの表示と非表示を切り替えている

  • <input type="password"> ---> ******
  • <input type="text"> ---> asdfgh

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?