Show/Hide Password Toggle

Beginner

This tutorial is from open-source community. Access the source code

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.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 91% completion rate. It has received a 100% positive review rate from learners.

Show/Hide Password Toggle

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.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.