← Components

Selection and input

Input OTP

Single-character slots for one-time codes. Digits drop in and squash; the caret pill slides along; a wrong code shakes the row; the right one pops the slots in a wave and merges them into one pill with a check.

Examples and variants

Verify

Two groups of three. 123456 succeeds; anything else shakes.

Try 123456, or any other code to see the shake.

Example
function OtpVerify() {
  const [code, setCode] = useState("")
  const [status, setStatus] = useState<"idle" | "error" | "success">("idle")
  return (
    <div className="flex flex-col items-center gap-stack-sm">
      <InputOTP
        length={6}
        groups={[3, 3]}
        value={code}
        status={status}
        onChange={(next) => {
          setCode(next)
          if (status !== "idle") setStatus("idle")
        }}
        onComplete={(full) =>
          window.setTimeout(() => setStatus(full === "123456" ? "success" : "error"), tokenMs("--duration-fast"))
        }
      />
      <p className="text-sm text-muted-foreground">
        {status === "success" ? "Verified" : status === "error" ? "Not right. Try 123456." : "Try 123456, or any other code to see the shake."}
      </p>
      {status !== "idle" ? (
        <Button size="sm" variant="ghost" onClick={() => { setCode(""); setStatus("idle") }}>
          Start over
        </Button>
      ) : null}
    </div>
  )
}

Letters and numbers

pattern="alphanumeric", four slots.

Example
function OtpLetters() {
  const [code, setCode] = useState("")
  return <InputOTP length={4} pattern="alphanumeric" label="Invite code" value={code} onChange={setCode} />
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/input-otp.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install cn lucide-react
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/input-otp.tsxinput-otp
      components/ui/input-otp.tsx
      "use client"
      
      import * as React from "react"
      import { CheckIcon } from "lucide-react"
      import { cn } from "cn"
      import { useGooTokens } from "@/components/motion/goo-layer"
      import { useMotionLevel } from "@/lib/motion/use-motion-level"
      
      /*
        Input OTP: single-character slots for one-time codes. One real input sits
        over the slots (autocomplete="one-time-code"), so typing, paste and SMS
        autofill all work. Digits drop into their slot and squash; the caret pill
        slides to the next slot; a paste fills left to right with a stagger.
        status="error" shakes the row once and flashes the slots; status="success"
        pops the slots in a wave, then merges them into one pill with a check (goo).
        Calm: no merge, no shake. Still: instant.
      */
      type Status = "idle" | "error" | "success"
      
      function InputOTP({
        length = 6,
        groups,
        value,
        onChange,
        onComplete,
        status = "idle",
        pattern = "digits",
        label = "Verification code",
        disabled,
        className,
      }: {
        length?: number
        /** Slot counts per group, e.g. [3, 3]. Groups are separated by a gap. */
        groups?: number[]
        value: string
        onChange: (value: string) => void
        /** Called once all slots are filled. */
        onComplete?: (value: string) => void
        status?: Status
        pattern?: "digits" | "alphanumeric"
        label?: string
        disabled?: boolean
        className?: string
      }) {
        const id = React.useId()
        const filterId = `otp-goo-${id.replace(/:/g, "")}`
        const goo = useGooTokens()
        const { level, ref } = useMotionLevel<HTMLDivElement>()
        const [focused, setFocused] = React.useState(false)
        // Per-slot stamp: changes only when that slot's character changes, so its drop replays alone.
        const [stamps, setStamps] = React.useState<number[]>(() => Array.from({ length }, () => 0))
        const [batchFrom, setBatchFrom] = React.useState(0)
        const sizes = groups && groups.reduce((a, b) => a + b, 0) === length ? groups : [length]
        const groupOf = sizes.flatMap((size, g) => Array.from({ length: size }, () => g))
        const gaps = sizes.length - 1
        const merged = status === "success" && level === "liquid"
        const active = Math.min(value.length, length - 1)
      
        function clean(raw: string) {
          const text = pattern === "digits" ? raw.replace(/\D/g, "") : raw.replace(/[^a-z0-9]/gi, "").toUpperCase()
          return text.slice(0, length)
        }
      
        function left(i: number) {
          if (merged) {
            // Close every gap; centre the pill and its check together in the original width.
            return `calc(${i} * var(--otp-slot-width) + ${gapTotal} / 2 - (var(--otp-slot-height) + var(--otp-gap)) / 2)`
          }
          return `calc(${i} * (var(--otp-slot-width) + var(--otp-gap)) + ${groupOf[i]} * var(--otp-group-gap))`
        }
      
        const gapTotal = `(${length - 1} * var(--otp-gap) + ${gaps} * var(--otp-group-gap))`
        const width = `calc(${length} * var(--otp-slot-width) + ${length - 1} * var(--otp-gap) + ${gaps} * var(--otp-group-gap))`
      
        return (
          <div
            ref={ref}
            data-slot="input-otp"
            data-status={status}
            data-merged={merged || undefined}
            className={cn("otp relative inline-flex items-center", className)}
          >
            <div className="otp-row relative h-(--otp-slot-height)" style={{ width }}>
              {level === "still" ? null : (
                <svg width="0" height="0" className="absolute" aria-hidden>
                  <filter id={filterId} x="-20%" y="-50%" width="140%" height="200%" colorInterpolationFilters="sRGB">
                    <feGaussianBlur in="SourceGraphic" stdDeviation={goo.blur} result="blur" />
                    <feColorMatrix in="blur" mode="matrix" values={`1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 ${goo.slope} ${goo.intercept}`} />
                  </filter>
                </svg>
              )}
              {/* Slot surfaces: one layer under the goo filter so they can merge. */}
              <div aria-hidden className="absolute inset-0" style={merged ? { filter: `url(#${filterId})` } : undefined}>
                {Array.from({ length }, (_, i) => (
                  <span
                    key={i}
                    className="otp-slot absolute top-0 h-full w-(--otp-slot-width) rounded-(--otp-slot-corner) bg-(--otp-slot-container) shadow-(--otp-slot-elevation)"
                    style={{ left: left(i), "--i": i } as React.CSSProperties}
                  />
                ))}
              </div>
              {/* Caret pill: slides to the slot you type next. */}
              {focused && !merged ? (
                <span
                  aria-hidden
                  className="otp-caret pointer-events-none absolute top-0 h-full w-(--otp-slot-width) rounded-(--otp-slot-corner) shadow-(--otp-caret)"
                  style={{ left: left(active) }}
                />
              ) : null}
              {/* Characters, crisp above the filter. */}
              {Array.from({ length }, (_, i) => {
                const char = value[i]
                const delay = char && i >= batchFrom ? i - batchFrom : 0
                return (
                  <span
                    key={i}
                    aria-hidden
                    className="otp-char absolute top-0 grid h-full w-(--otp-slot-width) place-items-center font-mono text-title text-(--otp-label)"
                    style={{ left: left(i), "--i": i } as React.CSSProperties}
                  >
                    {char ? (
                      <span key={stamps[i]} className="otp-glyph" style={{ "--d": delay } as React.CSSProperties}>
                        {char}
                      </span>
                    ) : null}
                  </span>
                )
              })}
              <input
                aria-label={label}
                aria-invalid={status === "error" || undefined}
                autoComplete="one-time-code"
                inputMode={pattern === "digits" ? "numeric" : "text"}
                maxLength={length}
                disabled={disabled}
                value={value}
                spellCheck={false}
                className="absolute inset-0 size-full cursor-text bg-transparent text-base text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed"
                onFocus={() => setFocused(true)}
                onBlur={() => setFocused(false)}
                onSelect={(event) => {
                  const input = event.currentTarget
                  const end = input.value.length
                  if (input.selectionStart !== end) input.setSelectionRange(end, end)
                }}
                onChange={(event) => {
                  const next = clean(event.target.value)
                  // Characters added in one change (a paste) animate in a stagger from the first new slot.
                  const first = [...next].findIndex((c, i) => c !== value[i])
                  setBatchFrom(first === -1 ? next.length : first)
                  setStamps((all) => all.map((stamp, i) => (next[i] !== value[i] ? stamp + 1 : stamp)))
                  onChange(next)
                  if (next.length === length && value.length !== length) onComplete?.(next)
                }}
              />
            </div>
            <span
              aria-hidden
              className="otp-check absolute top-0 inline-grid size-(--otp-slot-height) place-items-center rounded-full bg-(--otp-success) text-(--otp-success-label)"
              data-visible={status === "success" || undefined}
              style={{
                left: merged
                  ? `calc(${length} * var(--otp-slot-width) + ${gapTotal} / 2 - (var(--otp-slot-height) + var(--otp-gap)) / 2 + var(--otp-gap))`
                  : `calc(${width} + var(--otp-gap))`,
              }}
            >
              <CheckIcon className="size-(--size-icon-md)" />
            </span>
            <span className="sr-only" aria-live="polite">
              {status === "error" ? "That code is not right. Try again." : status === "success" ? "Code verified." : ""}
            </span>
          </div>
        )
      }
      
      export { InputOTP }
      

Imports

What the examples on this page import:

Imports
import { ArchiveIcon } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Chart } from "@/components/ui/chart"
import { DataTable, type DataTableColumn } from "@/components/ui/data-table"
import { InputOTP } from "@/components/ui/input-otp"
import { tokenMs } from "@/lib/motion/token-ms"

Anatomy

  1. 1Slot · --otp-slot-width, --otp-slot-height, --otp-slot-corner, --otp-slot-container, --otp-slot-elevation.
  2. 2Caret pill · --otp-caret; slides to the next slot.
  3. 3Group gap · --otp-gap between slots, plus --otp-group-gap between groups.
  4. 4States · Error --otp-error-container; success --otp-success-container and the check.

Props

PropTypeDefaultDescription
value, onChangestring, (value) => void—Controlled value.
lengthnumber6Slot count.
groupsnumber[]—Slots per group, e.g. [3, 3].
onComplete(value) => void—Called when every slot is filled.
status"idle" | "error" | "success""idle"Shake or merge.
pattern"digits" | "alphanumeric""digits"Allowed characters.
labelstring"Verification code"Accessible name.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--otp-slot-widthvar(--size-control-md)40pxsame
--otp-slot-heightvar(--size-control-lg)48pxsame
--otp-slot-cornervar(--shape-md)14pxsame
--otp-slot-containervar(--field-container)oklch(0.965 0.005 95)oklch(0.12 0 0)
--otp-slot-elevationvar(--field-elevation)0 1px 1px -0.5px oklch(0.22 0.01 260 / 7%), 0 2px 3px -1px oklch(0.22 0.01 260 / 10%), 0 4px 8px -4px oklch(0.22 0.01 260 / 6%)0 1px 2px oklch(0 0 0 / 35%), 0 2px 10px oklch(0 0 0 / 25%)
--otp-gapvar(--space-2)8pxsame
--otp-group-gapvar(--space-4)16pxsame
--otp-labelvar(--field-label)oklch(0.22 0.01 260)oklch(1 0 0)
--otp-caretvar(--field-focus-shadow)0 0 0 var(--state-field-stroke) color-mix(in oklch, var(--color-fg-default) var(--state-field-stroke-mix), transparent), var(--elevation-3)same
--otp-error-containervar(--color-danger-subtle)oklch(0.55 0.2 25 / 10%)oklch(0.68 0.18 22 / 16%)
--otp-success-containercolor-mix(in oklab, var(--color-success) 16%, var(--surface-container-lowest))color-mix(in oklab, var(--color-success) 16%, var(--surface-container-lowest))same
--otp-successvar(--otp-success-container)color-mix(in oklab, var(--color-success) 16%, var(--surface-container-lowest))same
--otp-success-labelvar(--color-success-fg)oklch(0.48 0.13 150)oklch(0.8 0.15 150)

Motion

TriggerWhat happensTokens
Type / pasteEach character drops and squashes; a paste fills left to right.--spring-bouncy, --duration-stagger
ErrorThe row shakes once; slots flash danger.--duration-medium
SuccessSlots pop in a wave, then merge into one pill (goo); the check pops.--spring-snappy, --goo-blur

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • One real input with autocomplete="one-time-code", so paste and SMS autofill work.
  • Errors and success are announced.
  • Calm drops the shake and merge; still is instant.

Usage

Do

  • Use for verification codes.

Don’t

  • Don't use for passwords or PINs you must hide.

Code

components/ui/input-otp.tsx
"use client"

import * as React from "react"
import { CheckIcon } from "lucide-react"
import { cn } from "cn"
import { useGooTokens } from "@/components/motion/goo-layer"
import { useMotionLevel } from "@/lib/motion/use-motion-level"

/*
  Input OTP: single-character slots for one-time codes. One real input sits
  over the slots (autocomplete="one-time-code"), so typing, paste and SMS
  autofill all work. Digits drop into their slot and squash; the caret pill
  slides to the next slot; a paste fills left to right with a stagger.
  status="error" shakes the row once and flashes the slots; status="success"
  pops the slots in a wave, then merges them into one pill with a check (goo).
  Calm: no merge, no shake. Still: instant.
*/
type Status = "idle" | "error" | "success"

function InputOTP({
  length = 6,
  groups,
  value,
  onChange,
  onComplete,
  status = "idle",
  pattern = "digits",
  label = "Verification code",
  disabled,
  className,
}: {
  length?: number
  /** Slot counts per group, e.g. [3, 3]. Groups are separated by a gap. */
  groups?: number[]
  value: string
  onChange: (value: string) => void
  /** Called once all slots are filled. */
  onComplete?: (value: string) => void
  status?: Status
  pattern?: "digits" | "alphanumeric"
  label?: string
  disabled?: boolean
  className?: string
}) {
  const id = React.useId()
  const filterId = `otp-goo-${id.replace(/:/g, "")}`
  const goo = useGooTokens()
  const { level, ref } = useMotionLevel<HTMLDivElement>()
  const [focused, setFocused] = React.useState(false)
  // Per-slot stamp: changes only when that slot's character changes, so its drop replays alone.
  const [stamps, setStamps] = React.useState<number[]>(() => Array.from({ length }, () => 0))
  const [batchFrom, setBatchFrom] = React.useState(0)
  const sizes = groups && groups.reduce((a, b) => a + b, 0) === length ? groups : [length]
  const groupOf = sizes.flatMap((size, g) => Array.from({ length: size }, () => g))
  const gaps = sizes.length - 1
  const merged = status === "success" && level === "liquid"
  const active = Math.min(value.length, length - 1)

  function clean(raw: string) {
    const text = pattern === "digits" ? raw.replace(/\D/g, "") : raw.replace(/[^a-z0-9]/gi, "").toUpperCase()
    return text.slice(0, length)
  }

  function left(i: number) {
    if (merged) {
      // Close every gap; centre the pill and its check together in the original width.
      return `calc(${i} * var(--otp-slot-width) + ${gapTotal} / 2 - (var(--otp-slot-height) + var(--otp-gap)) / 2)`
    }
    return `calc(${i} * (var(--otp-slot-width) + var(--otp-gap)) + ${groupOf[i]} * var(--otp-group-gap))`
  }

  const gapTotal = `(${length - 1} * var(--otp-gap) + ${gaps} * var(--otp-group-gap))`
  const width = `calc(${length} * var(--otp-slot-width) + ${length - 1} * var(--otp-gap) + ${gaps} * var(--otp-group-gap))`

  return (
    <div
      ref={ref}
      data-slot="input-otp"
      data-status={status}
      data-merged={merged || undefined}
      className={cn("otp relative inline-flex items-center", className)}
    >
      <div className="otp-row relative h-(--otp-slot-height)" style={{ width }}>
        {level === "still" ? null : (
          <svg width="0" height="0" className="absolute" aria-hidden>
            <filter id={filterId} x="-20%" y="-50%" width="140%" height="200%" colorInterpolationFilters="sRGB">
              <feGaussianBlur in="SourceGraphic" stdDeviation={goo.blur} result="blur" />
              <feColorMatrix in="blur" mode="matrix" values={`1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 ${goo.slope} ${goo.intercept}`} />
            </filter>
          </svg>
        )}
        {/* Slot surfaces: one layer under the goo filter so they can merge. */}
        <div aria-hidden className="absolute inset-0" style={merged ? { filter: `url(#${filterId})` } : undefined}>
          {Array.from({ length }, (_, i) => (
            <span
              key={i}
              className="otp-slot absolute top-0 h-full w-(--otp-slot-width) rounded-(--otp-slot-corner) bg-(--otp-slot-container) shadow-(--otp-slot-elevation)"
              style={{ left: left(i), "--i": i } as React.CSSProperties}
            />
          ))}
        </div>
        {/* Caret pill: slides to the slot you type next. */}
        {focused && !merged ? (
          <span
            aria-hidden
            className="otp-caret pointer-events-none absolute top-0 h-full w-(--otp-slot-width) rounded-(--otp-slot-corner) shadow-(--otp-caret)"
            style={{ left: left(active) }}
          />
        ) : null}
        {/* Characters, crisp above the filter. */}
        {Array.from({ length }, (_, i) => {
          const char = value[i]
          const delay = char && i >= batchFrom ? i - batchFrom : 0
          return (
            <span
              key={i}
              aria-hidden
              className="otp-char absolute top-0 grid h-full w-(--otp-slot-width) place-items-center font-mono text-title text-(--otp-label)"
              style={{ left: left(i), "--i": i } as React.CSSProperties}
            >
              {char ? (
                <span key={stamps[i]} className="otp-glyph" style={{ "--d": delay } as React.CSSProperties}>
                  {char}
                </span>
              ) : null}
            </span>
          )
        })}
        <input
          aria-label={label}
          aria-invalid={status === "error" || undefined}
          autoComplete="one-time-code"
          inputMode={pattern === "digits" ? "numeric" : "text"}
          maxLength={length}
          disabled={disabled}
          value={value}
          spellCheck={false}
          className="absolute inset-0 size-full cursor-text bg-transparent text-base text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed"
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onSelect={(event) => {
            const input = event.currentTarget
            const end = input.value.length
            if (input.selectionStart !== end) input.setSelectionRange(end, end)
          }}
          onChange={(event) => {
            const next = clean(event.target.value)
            // Characters added in one change (a paste) animate in a stagger from the first new slot.
            const first = [...next].findIndex((c, i) => c !== value[i])
            setBatchFrom(first === -1 ? next.length : first)
            setStamps((all) => all.map((stamp, i) => (next[i] !== value[i] ? stamp + 1 : stamp)))
            onChange(next)
            if (next.length === length && value.length !== length) onComplete?.(next)
          }}
        />
      </div>
      <span
        aria-hidden
        className="otp-check absolute top-0 inline-grid size-(--otp-slot-height) place-items-center rounded-full bg-(--otp-success) text-(--otp-success-label)"
        data-visible={status === "success" || undefined}
        style={{
          left: merged
            ? `calc(${length} * var(--otp-slot-width) + ${gapTotal} / 2 - (var(--otp-slot-height) + var(--otp-gap)) / 2 + var(--otp-gap))`
            : `calc(${width} + var(--otp-gap))`,
        }}
      >
        <CheckIcon className="size-(--size-icon-md)" />
      </span>
      <span className="sr-only" aria-live="polite">
        {status === "error" ? "That code is not right. Try again." : status === "success" ? "Code verified." : ""}
      </span>
    </div>
  )
}

export { InputOTP }