
You might have seen on many websites, that password fields has a nice icon to show / hide password. In this react js tutorial, we are going to build a password form field with option to show and hide password.
Step 1: Create a password field with eye icon
Create a simple password input field. Add an icon to toggle password visibility. I have used two icons for this: eye.svg and eye-off.svg
You can find these icons in the source code at GitHub (Link is at the bottom).
<div className='form-item'>
<input type="password" placeholder='enter your password' />
<span className='password-icon' <img src={eye} alt="icon" /></span>
</div>
Step 2: Import visibility icon
import eye from './images/eye.svg'
import eyeOff from './images/eye-off.svg'
Step 3: Create state
Create two constants, one for icon and other for input type.
const [icon, setIcon] = useState(eye);
const [inputType, setInputType] = useState('password');
Step 4: Use react variables in the form
Use icon and input type variables in the form.
<div className='form-item'>
<input type={inputType} placeholder='enter your password' />
<span className='password-icon'<img src={icon} alt="icon" /></span>
</div>
Step 5: Add onClick Event
Add an onclick event to the icon to toggle icon and input type.
<div className='form-item'>
<input type={inputType} placeholder='enter your password' />
<span className='password-icon' onClick={togglePassword}><img src={icon} alt="icon" /></span>
</div>
Step 6: Create onclick function
const togglePassword = () => {
if(inputType === 'password') {
setInputType('text')
setIcon(eyeOff)
} else {
setInputType('password')
setIcon(eye)
}
}
Step 7: Add Styling
Now let's add some css to style the form.
input[type="text"],
input[type="password"] {
width: 100%;
max-width: 400px;
border: 0;
outline: none;
}
.form-item {
background-color: #ffffff;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
box-shadow: 0 0 6px #B2AFD3;
}
.password-icon {
cursor: pointer;
}
Full Code
import './css/style.css';
import eye from './images/eye.svg'
import eyeOff from './images/eye-off.svg'
import { useState } from 'react';
function App() {
const [icon, setIcon] = useState(eye);
const [inputType, setInputType] = useState('password');
const togglePassword = () => {
if(inputType === 'password') {
setInputType('text')
setIcon(eyeOff)
} else {
setInputType('password')
setIcon(eye)
}
}
return (
<>
<div className='container'>
<div className='content'>
<h2>Create your password</h2>
<div className='form-item'>
<input type={inputType} placeholder='enter your password' />
<span className='password-icon' onClick={togglePassword}><img src={icon} alt="icon" /></span>
</div>
</div>
</div>
</>
);
}
export default App;
Demo and Download
Demo: https://react-toggle-password-visibility.vercel.app/
Download Source code from GitHub:
https://github.com/dewdot/React-Toggle-Password-Visibility
Video Tutorial
Category