Two Factor Auth

Auth & User

Two-factor authentication code input.

Preview

Two-Factor Authentication

Enter the 6-digit code from your authenticator app

Usage

example.jsx
import { TwoFactorAuth } from "@/components/ui/two-factor-auth";

export default function Example() {
  return <TwoFactorAuth />;
}

Source Code

Copy this file into components/ui/two-factor-auth.jsx in your project.

two-factor-auth.jsx
"use client";

import { forwardRef, useState, useRef } from "react";
import { cn } from "@/lib/utils";

const TwoFactorAuth = forwardRef(({ className, length = 6, onComplete, ...props }, ref) => {
  const [values, setValues] = useState(Array(length).fill(""));
  const inputs = useRef([]);

  const handleChange = (idx, val) => {
    if (!/^\d*$/.test(val)) return;
    const newValues = [...values];
    newValues[idx] = val.slice(-1);
    setValues(newValues);
    if (val && idx < length - 1) inputs.current[idx + 1]?.focus();
    const code = newValues.join("");
    if (code.length === length && newValues.every((v) => v)) onComplete?.(code);
  };

  const handleKeyDown = (idx, e) => {
    if (e.key === "Backspace" && !values[idx] && idx > 0) inputs.current[idx - 1]?.focus();
  };

  return (
    <div ref={ref} className={cn("mx-auto max-w-sm space-y-4 text-center", className)} {...props}>
      <div>
        <h3 className="text-lg font-semibold">Two-Factor Authentication</h3>
        <p className="mt-1 text-sm text-muted-foreground">Enter the 6-digit code from your authenticator app</p>
      </div>
      <div className="flex justify-center gap-2">
        {values.map((v, i) => (
          <input key={i} ref={(el) => (inputs.current[i] = el)}
            type="text" inputMode="numeric" maxLength={1} value={v}
            onChange={(e) => handleChange(i, e.target.value)}
            onKeyDown={(e) => handleKeyDown(i, e)}
            className="h-12 w-10 rounded-md border bg-background text-center text-lg font-bold focus:outline-none focus:ring-2 focus:ring-ring"
          />
        ))}
      </div>
    </div>
  );
});
TwoFactorAuth.displayName = "TwoFactorAuth";

export { TwoFactorAuth };

Quick Install

Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.

npm install clsx tailwind-merge