|
| 1 | +import React, { useState } from "react"; |
| 2 | +import { |
| 3 | + IconButton, |
| 4 | + InputAdornment, |
| 5 | +} from "@mui/material"; |
| 6 | +import { Visibility, VisibilityOff } from "@mui/icons-material"; |
| 7 | +import { TextValidator } from "react-material-ui-form-validator"; |
| 8 | + |
| 9 | +interface PasswordFieldProps { |
| 10 | + password: string; |
| 11 | + setPassword: React.Dispatch<React.SetStateAction<string>>; |
| 12 | + label?: string; |
| 13 | +} |
| 14 | + |
| 15 | +const PasswordField = ({password, setPassword, label = "Password" }: PasswordFieldProps) => { |
| 16 | + const [showPassword, setShowPassword] = useState<boolean>(false); |
| 17 | + |
| 18 | + const handleClickShowPassword = () => setShowPassword((show) => !show); |
| 19 | + |
| 20 | + const handleMouseDownPassword = ( |
| 21 | + event: React.MouseEvent<HTMLButtonElement>, |
| 22 | + ) => { |
| 23 | + event.preventDefault(); |
| 24 | + }; |
| 25 | + |
| 26 | + const errorForTwoChar = "Enter at least two characters."; |
| 27 | + |
| 28 | + return ( |
| 29 | + <TextValidator |
| 30 | + validators={["minStringLength:2"]} |
| 31 | + errorMessages={[errorForTwoChar]} |
| 32 | + id="password" |
| 33 | + name="password" |
| 34 | + value={password} |
| 35 | + label={label} |
| 36 | + type={showPassword ? "text" : "password"} |
| 37 | + InputProps={{ |
| 38 | + endAdornment: ( |
| 39 | + <InputAdornment position="end"> |
| 40 | + <IconButton |
| 41 | + aria-label="toggle password visibility" |
| 42 | + onClick={handleClickShowPassword} |
| 43 | + onMouseDown={handleMouseDownPassword} |
| 44 | + edge="end" |
| 45 | + > |
| 46 | + {showPassword ? <VisibilityOff /> : <Visibility />} |
| 47 | + </IconButton> |
| 48 | + </InputAdornment> |
| 49 | + ), |
| 50 | + }} |
| 51 | + variant="outlined" |
| 52 | + required |
| 53 | + fullWidth |
| 54 | + inputProps={{ |
| 55 | + onChange: (event: React.ChangeEvent<HTMLInputElement>) => |
| 56 | + setPassword(event.target.value), |
| 57 | + "data-testid": "password", |
| 58 | + }} |
| 59 | + /> |
| 60 | + ); |
| 61 | +}; |
| 62 | + |
| 63 | +export default PasswordField; |
0 commit comments