Password Input
React
Easy
Objective
Create a password input React component
Requirements
The component should be called
PasswordInput
It should be able to handle user input and pass the value to its parent
This should be a controlled component, with the parent setting the value
You can use a simple
useState
for this
The component should display the password as masked or hidden
But it should provide an option for the user to toggle the visibility into plaintext
This can be either text ("show"|"hide") or via icons
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
import React, { useState } from 'react';
function PasswordInput (props) {
const { value, controlFunc } = props;
const [showPassword, setShowPassword] = useState(false);
// Pass the new value to the parent
function handleChange (event) {
controlFunc(event.target.value);
}
// Toggle the visibility of the password
function toggleVisibility () {
setShowPassword(!showPassword);
}
return (
<div>
<input
type={showPassword ? 'text' : 'password'}
value={value}
onChange={handleChange}
/>
<button onClick={toggleVisibility}>
{showPassword ? 'Hide' : 'Show'}
</button>
</div>
)
}
export default PasswordInput;
Click to reveal