DEV Community

Cover image for How to display a password in a form input using React Hooks
oteri
oteri

Posted on • Edited on

4 3

How to display a password in a form input using React Hooks

Have you ever wondered how to create an input field with an icon that helps you check the password when you type? In this article, we would explore the ability to recreate this task as shown on different modern websites, which you can use from now on.

Prerequisite

A basic understanding of React and how to use hooks, useState.

Goals

By the end of this article, we would have built a simple input field that accepts a password and the ability to check the password as you type.

Demo

Getting started

We need to create a component folder and include a .js file that would help us write JSX template syntax inside of JavaScript.

import { useState } from "react";
import { FiEye } from "react-icons/fi";
import "../styles.css";

const PasswordRevealer = () => {
  const [shown, setShown] = useState(false);

  return (
    <>
      <h1>Password Revealer</h1>
      <div className="input">
        <input type={shown ? "text" : "password"} />
        <FiEye className="reveal" onClick={() => setShown(!shown)} />
      </div>
    </>
  );
};

export default PasswordRevealer;
Enter fullscreen mode Exit fullscreen mode

Using the hooks, useState, we were able to declare the state shown to false initially till the user types in a password; it doesn't show till the user clicks the icon which listens to action with an event listener onClick, which toggles the visibility of the password on and off and update its state with setShown.

After that is done, call the PasswordRevealer.js file into the home component App.js.

// Main component
import "./styles.css";
import PasswordRevealer from "./components/PasswordRevealer";

export default function App() {
  return (
    <div className="App">
      <PasswordRevealer />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

The method above helps to give users of your website the chance to know the password they are entering, as this can be of great benefits when signing or registering on a website. So I would encourage you to give this method a try as it improves the website's experience and usability.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more