Show/hide password toggle
React, Components, Input, State · Nov 25, 2020

Renders a password input field with a reveal button.
- Use the
useState()
hook to create theshown
state variable and set its value tofalse
. - When the
<button>
is clicked, executesetShown
, toggling thetype
of the<input>
between'text'
and'password'
.
const PasswordRevealer = ({ value }) => {
const [shown, setShown] = React.useState(false);
return (
<>
<input type={shown ? 'text' : 'password'} value={value} />
<button onClick={() => setShown(!shown)}>Show/Hide</button>
</>
);
};
ReactDOM.render(<PasswordRevealer />, document.getElementById('root'));