Password Input

React
Easy

Objective

Create a password input React component

Requirements

  1. The component should be called PasswordInput

  2. It should be able to handle user input and pass the value to its parent

    1. This should be a controlled component, with the parent setting the value

    2. You can use a simple useState for this

  3. The component should display the password as masked or hidden

    1. But it should provide an option for the user to toggle the visibility into plaintext

    2. 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