In this small task, we will implement Showing and Hiding password using React JS.

Steps:

  • We will first create a state variable (by using useState) based on which we will either show the password or hide it.
  • We will create an input element whose type is password initially.
  • We will provide a check box which can be checked or unchecked to show or hide the password
  • When the user clicks on the check box, we will simply reverse the value of the state variable to show the password or hide it

Code:

import React, { useState } from 'react';

function ShowHidePassword() {

    const [showPassword, setShowPassword] = useState(false);

    const handleShowHidePassword = () => {
        setShowPassword(!showPassword);
    }

    return <div>
        <div className="mb-3">
            <label for="exampleInputPassword1" className="form-label">Password</label>
            <input type={showPassword ? "text" : "password"} className="form-control" id="exampleInputPassword1" />
        </div>
        <div className="mb-3 form-check">
            <input type="checkbox" className="form-check-input" id="exampleCheck1"
                onClick={handleShowHidePassword} />
            <label className="form-check-label" for="exampleCheck1"> {showPassword ? 'Hide' : 'Show'} password </label>
        </div>
    </div>;
}

export default ShowHidePassword;

You can check this post if you want to achieve the same functionality using just JavaScript
How to Implement Show / Hide Password in JavaScript without using any library or framework