using useState Hook

We will be using useState variable with react funtional component to store and update the show and hide state and store password along with the checkbox linked with this state.

Example: Created a password input that changes to type text if the checkbox is clicked.

Javascript




// Filename - App.js
 
import React, { useState } from "react";
 
import "./App.css";
 
function App() {
    const [password, setPassword] = useState("");
    const [showPassword, setShowPassword] = useState(false);
    return (
        <div className="App">
            <h1 className="geeks">w3wiki</h1>
            <h3>React Example to Show/Hide password</h3>
            <div>
                <label for="pass">Enter password: </label>
                <input
                    id="pass"
                    type={
                        showPassword ? "text" : "password"
                    }
                    value={password}
                    onChange={(e) =>
                        setPassword(e.target.value)
                    }
                />
                <br />
                <br />
                <label for="check">Show Password</label>
                <input
                    id="check"
                    type="checkbox"
                    value={showPassword}
                    onChange={() =>
                        setShowPassword((prev) => !prev)
                    }
                />
            </div>
            <br />
        </div>
    );
}
 
export default App;


CSS




/* Filename - App.css */
 
.App {
    text-align: center;
    margin: auto;
}
 
.geeks {
    color: green;
}


Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

How to show and hide Password in ReactJS?

To show and hide passwords in React JS we can simply use the password input with an input to select the show and hide state. The user might need to see what has he used as the password to verify which is an important concept in login and registration forms. We can create this type of password input using state and also with the help of external libraries.

Similar Reads

Prerequisites

React JS React JS useState hook Material UI...

Creating React Application:

Step 1: Create a React application using the following command:...

Project Structure

It will look like the following....

Approach 1: using useState Hook

We will be using useState variable with react funtional component to store and update the show and hide state and store password along with the checkbox linked with this state....

Approach 2: using MUI Inputs

...

Contact Us