RevealPasswordToggle.tsx raw

   1  import { EyeIcon, EyeOffIcon } from "lucide-react";
   2  import { useEffect, useState } from "react";
   3  import { cn } from "src/lib/utils";
   4  
   5  type Props = {
   6    onChange: (isRevealed: boolean) => void;
   7    isRevealed?: boolean;
   8    iconClass?: string;
   9  };
  10  
  11  export default function RevealPasswordToggle({
  12    onChange,
  13    isRevealed,
  14    iconClass,
  15  }: Props) {
  16    const [_isRevealed, setRevealed] = useState(false);
  17  
  18    // toggle the button if password view is handled by component itself
  19    useEffect(() => {
  20      if (typeof isRevealed !== "undefined") {
  21        setRevealed(isRevealed);
  22      }
  23    }, [isRevealed]);
  24  
  25    return (
  26      <button
  27        type="button"
  28        tabIndex={-1}
  29        className="flex justify-center items-center w-10 h-8"
  30        onClick={() => {
  31          setRevealed(!_isRevealed);
  32          onChange(!_isRevealed);
  33        }}
  34      >
  35        {_isRevealed ? (
  36          <EyeOffIcon className={cn("h-4 w-4", iconClass)} />
  37        ) : (
  38          <EyeIcon className={cn("h-4 w-4", iconClass)} />
  39        )}
  40      </button>
  41    );
  42  }
  43