Introduction
In this lab, we will learn how to create a password input field with a toggle button that allows users to show or hide their password. This will be done using the useState() hook in React. By the end of this lab, you will have a better understanding of how to manage state in React and how to create a simple yet useful component for user interaction.
Show/Hide Password Toggle
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
The following code renders a password input field with a reveal button. It uses the useState() hook to create the shown state variable and set its initial value to false. When the Show/Hide button is clicked, the setShown function is called, toggling the type 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.createRoot(document.getElementById("root")).render(
<PasswordRevealer />
);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Show/Hide Password Toggle lab. You can practice more labs in LabEx to improve your skills.