React password eye icon toggle

Eye open/closed to mask/show the actual password in react

by Stephane de Luca

HTML

<html>
<header>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</header>
<body>

<div id="app"></div>

</body>
</html>

React

const {useState, useEffect, useRef} = React
function classNames(className, options) {
	const r = className + ' ' + Object
  .keys(options)
  .filter(className => options[className])
  .join(' ')
  console.log(r)
	return r
}


function PasswordVisibility({showPassword, setShowPassword, isNotEmpty}) {

	console.log('PasswordVisibility.showPassword',showPassword)
  
  return (<span
        className={classNames('icon is-small is-right has-text-primary', {
        'pr-6': isNotEmpty
        })}
        
        onClick={e => {
            e.preventDefault()
            setShowPassword(!showPassword)
        }}
        >
        <i
            className={classNames('fas', {
                'fa-eye-slash':  showPassword,
                'fa-eye':       !showPassword,
            })}
            style={{
                pointerEvents: 'all',
                cursor: 'pointer',
            }}
        />
        show:<br/>{''+showPassword}
    </span>
    )
}





function PasswordField(props) {
	const {field, isConfirmation, passwordCreation, values, errors, handleChange, isSubmitting, disabled} = props
	const [showPassword, setShowPassword] = useState(false)


	const name = isConfirmation ? 'passwordConfirmation' : 'password'

console.log(props, 'name:',name, )

const passwordValue = values[name]
	const passwordError = errors[name]
  
  
  console.log(field, isConfirmation, passwordCreation, values, errors, handleChange, isSubmitting, disabled, name, passwordValue, passwordError)
  
	return (<div>
		<input id={name}
			type={showPassword ? 'text' : 'password'}
			name={name}
			placeholder={isConfirmation ? 'Confirm your password' : 'Your password'}
			onChange={handleChange}
			value={passwordValue || ''}
			required
			disabled={disabled}
			autoComplete={passwordCreation ? (isConfirmation ? '' :'new-password') : ''}
		/>
		
		<PasswordVisibility 
      showPassword={showPassword} 
      setShowPassword={setShowPassword} 
      isNotEmpty={true}
    ...