Quantcast
Viewing all articles
Browse latest Browse all 25

Toggle Password Visibility with Tailwind CSS and Next.js

Image may be NSFW.
Clik here to view.
A sneak peak of the component that we are going to build

Today, we’re going to build a simple password field with a toggle button to show or hide the password. This is a common UI element that improves user experience by allowing users to check their input without retyping.

We’ll create this using React with Next.js and style it using Tailwind CSS. The implementation is straightforward. We’ll use React’s useState hook to toggle the input type between password and text. Here’s how it works:

Code

"use client";

import { useState } from "react";
import { Eye, EyeOff } from "lucide-react";

export default function PasswordField() {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => setIsVisible(prevState => !prevState);

  return (
    <div className="relative">
      <input
        id="password"
        type={isVisible ? "text" : "password"}
        className="w-full text-sm text-slate-600 bg-white border border-slate-300 appearance-none rounded-lg ps-3.5 pe-10 py-2.5 outline-none focus:bg-white focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100"
        placeholder="Enter your password..."
        aria-label="Password"
        required
      />
      <button
        className="absolute inset-y-0 end-0 flex items-center z-20 px-2.5 cursor-pointer text-gray-400 rounded-e-md focus:outline-none focus-visible:text-indigo-500 hover:text-indigo-500 transition-colors"
        type="button"
        onClick={toggleVisibility}
        aria-label={isVisible ? "Hide password" : "Show password"}
        aria-pressed={isVisible}
        aria-controls="password"
      >
        {isVisible ? (
          <EyeOff size={20} aria-hidden="true" />
        ) : (
          <Eye size={20} aria-hidden="true" />
        )}
      </button>
    </div>
  );
}

This component is both functional and user-friendly, adhering to best practices for user experience and accessibility – we used accessibility attributes like aria-label, aria-pressed, and aria-controls. It’s a solid foundation that you can easily integrate into your Next.js app and customize as you wish.

The post Toggle Password Visibility with Tailwind CSS and Next.js appeared first on Cruip.


Viewing all articles
Browse latest Browse all 25

Trending Articles