Sign in with a code
Email first, then a six-digit code, with the field marked when it is wrong.
83 lines · React · Tailwind 4
Install
$ bunx shadcn@latest add @blocco/sign-in-codeCode
import { useRef, useState } from "react";
import { Field, Input } from "@/registry/blocco/ui/field";
import { Button } from "@/registry/blocco/ui/button";
import { OtpInput } from "@/registry/blocco/ui/otp";
import { BusyContent } from "@/registry/blocco/ui/spinner";
/**
* Email first, then a six-digit code. A wrong address marks the field and
* says why in its label row; the submit button never greys out.
*/
export default function SignInCode() {
const [step, setStep] = useState<"email" | "code">("email");
const [email, setEmail] = useState("");
const [error, setError] = useState<string>();
const [code, setCode] = useState("");
const [busy, setBusy] = useState(false);
const input = useRef<HTMLInputElement>(null);
return (
<section className="grid min-h-[36rem] place-items-center px-6 py-16">
<div className="w-full max-w-sm rounded-2xl bg-surface p-7 smooth-shadow-ring-xs">
{step === "email" ? (
<form
noValidate
onSubmit={(e) => {
e.preventDefault();
if (!/^\S+@\S+\.\S+$/.test(email)) {
setError(email ? "Not an email address" : "Required");
input.current?.focus();
return;
}
setError(undefined);
setBusy(true);
setTimeout(() => {
setBusy(false);
setStep("code");
}, 900);
}}
>
<h1 className="text-xl font-semibold">Sign in</h1>
<p className="mt-1 text-sm text-muted">
We send a code to your inbox. No password to remember.
</p>
<Field label="Email" error={error} className="mt-6">
<Input
ref={input}
type="email"
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@company.com"
/>
</Field>
<Button type="submit" variant="primary" className="mt-5 h-11 w-full justify-center">
<BusyContent busy={busy}>Send code</BusyContent>
</Button>
</form>
) : (
<div>
<h1 className="text-xl font-semibold">Check your inbox</h1>
<p className="mt-1 text-sm text-pretty text-muted">
We sent a six-digit code to <span className="font-mono text-text">{email}</span>.
</p>
<OtpInput value={code} onChange={setCode} autoFocus className="mt-6" />
<div className="mt-6 flex items-center justify-between text-sm">
<button
type="button"
className="cursor-pointer text-muted hover:text-text"
onClick={() => setStep("email")}
>
Use another email
</button>
<button type="button" className="cursor-pointer text-accent hover:underline">
Send it again
</button>
</div>
</div>
)}
</div>
</section>
);
}