0
(0)

For today I have a really short article for you. It is about sneak peeking the password field, to check what you actually wrote behind those bullets in your password input.

Let me provide you with the code:

The TSX file:

import './PasswordInput.css';
import React, { useState } from 'react';

const PasswordInput = ():JSX.Element => {
    const [pwSecurityDisabled, setPwSecurityDisabled] = useState(false);

    return (
        <div className={`togglePasswordSecurityWrapper ${pwSecurityDisabled ? 'shown' : ''}`}>
            <input type={pwSecurityDisabled ? `text` : 'password'} />
            <button 
                    className="togglePasswordSecurity" 
                    onClick={() => setPwSecurityDisabled(!pwSecurityDisabled)}>
                &#128065;
            </button>
        </div>
    )
}

export default PasswordInput;

The CSS file:

.togglePasswordSecurityWrapper {
    position: relative;
    display: inline-block;
}
.togglePasswordSecurityWrapper input {
    font-size: 30px;
    border: 2px solid #ccc;
    padding: 10px
}
.shown .togglePasswordSecurity {
    text-decoration: none;
    color: red;
}
.togglePasswordSecurity {
    background: none;
    border:0;
    position: absolute;
    right:0;
    height: 100%;
    cursor: pointer;
    font-size: 30px;
    line-height: 1;
    text-decoration: line-through
}

The explanation

The workflow is the following: When user clicks on the eye icon(the button element) we toggle the boolean value that is stored in the pwSecurityDisabled(password security disabled) state, which initially is false(security of the password is enabled, characters are hidden).

When the pwSecurityDisabled state get’s a true value 2 things are going to happen:

The container of the input get’s a “shown” class, that will make the eye get a line-through effect and the input’s type changes to “text”. This way the password is shown. On onClick event we are always setting the opposite of the pwSecurityDisabled state’s value.

Note: Of course the “shown” class you can add also directly on the button if you want, I just added on the parent element, to affect both input and button in case I want a collective style change.

Fun fact: The &#128065; is a HTML entity of a UTF character representing the eye icon.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in: