Show/Hide Password Toggle

ReactReactBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38358{{"`Show/Hide Password Toggle`"}} react/event_handling -.-> lab-38358{{"`Show/Hide Password Toggle`"}} react/conditional_render -.-> lab-38358{{"`Show/Hide Password Toggle`"}} react/hooks -.-> lab-38358{{"`Show/Hide Password Toggle`"}} react/use_state_reducer -.-> lab-38358{{"`Show/Hide Password Toggle`"}} end

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.

Other React Tutorials you may like