Input OTP
Accessible one-time password component with copy paste functionality.
Installation
Install the following dependencies:
pnpm add input-otp
Copy and paste the following code into your project.
"use client";
import { OTPInput, OTPInputContext } from "input-otp";
import { useContext } from "react";
import { cn } from "~/utils/tailwind";
function InputOTP({
className,
containerClassName,
...props
}: React.ComponentProps<typeof OTPInput>) {
return (
<OTPInput
containerClassName={cn(
"flex items-center gap-x-3 has-[:disabled]:opacity-50",
containerClassName,
)}
className={cn("disabled:cursor-not-allowed", className)}
{...props}
/>
);
}
function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
return <div className={cn("flex items-center", className)} {...props} />;
}
function InputOTPSlot({
index,
className,
...props
}: React.ComponentProps<"div"> & { index: number }) {
const inputOTPContext = useContext(OTPInputContext);
const slot = inputOTPContext.slots[index];
const { char, isActive } = slot ?? {
char: "",
isActive: false,
};
return (
<div
className={cn(
"relative flex h-14 w-10 items-center justify-center border-y border-r border-input text-4 transition-all",
"first:rounded-l-1.5 first:border-l last:rounded-r-1.5",
isActive && "z-10 ring-1 ring-ring",
className,
)}
{...props}
>
{char}
</div>
);
}
function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
return (
<div
role="separator"
className="h-1 w-3 rounded-full bg-border"
{...props}
/>
);
}
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
Update the import paths to match your project setup.
Add the following animations to your tailwind.config.ts
file.
import { type Config } from "tailwindcss";
export default {
darkMode: ["class"],
content: ["./src/**/*.tsx"],
theme: {
extend: {
animation: {
"caret-blink": "caret-blink 1.25s ease-out infinite",
},
keyframes: {
"caret-blink": {
"0%,70%,100%": { opacity: "1" },
"20%,50%": { opacity: "0" },
},
},
},
},
plugins: [require("tailwindcss-animate")],
} satisfies Config;
Usage
import {
InputOTP,
InputOTPGroup,
InputOTPSeparator,
InputOTPSlot,
} from "~/components/ui/InputOTP";
<InputOTP maxLength={6}>
<InputOTPGroup>
<InputOTPSlot index={0} />
<InputOTPSlot index={1} />
<InputOTPSlot index={2} />
</InputOTPGroup>
<InputOTPSeparator />
<InputOTPGroup>
<InputOTPSlot index={3} />
<InputOTPSlot index={4} />
<InputOTPSlot index={5} />
</InputOTPGroup>
</InputOTP>
Examples
Pattern
Use the pattern
prop to define a custom regex pattern for the input.
Separator
Use <InputOTPSeparator />
to add a separator between the groups of input.
Controlled
Use the value
and onChange
props to control the input value.
Enter your one-time password.