Pin Input
A short code entered one character to a box, for two-factor and verification codes.
Use it for a code of known length that somebody reads off another screen: a two-factor code, an email verification code, a pairing code. Typing fills a box and moves on, Backspace steps back, and a pasted code is dealt out across the boxes.
The value is a single string with no gaps, so a character typed in a later box lands in the first empty one.
newt-pin"use client"
import * as React from "react"
import { PinInput } from "@/registry/bases/newt/ui/pin-input"
export default function PinInputDemo() {
const [code, setCode] = React.useState("481")
const [status, setStatus] = React.useState("Enter the 6-digit code")
return (
<div className="flex flex-col items-center gap-3">
<PinInput
label="Two-factor code"
groupSize={3}
value={code}
onValueChange={(next) => {
setCode(next)
if (next.length < 6) setStatus("Enter the 6-digit code")
}}
onComplete={(next) => setStatus(`Checking ${next}…`)}
/>
<p className="text-xs text-newt-text-muted" aria-live="polite">
{status}
</p>
</div>
)
}<script setup lang="ts">
import { ref, watch } from "vue"
import { PinInput } from "~~/registry/bases/newt/ui/pin-input"
const code = ref("481")
const status = ref("Enter the 6-digit code")
watch(code, (next) => {
if (next.length < 6) status.value = "Enter the 6-digit code"
})
</script>
<template>
<div class="flex flex-col items-center gap-3">
<PinInput
v-model="code"
label="Two-factor code"
:group-size="3"
@complete="status = `Checking ${$event}…`"
/>
<p class="text-xs text-newt-text-muted" aria-live="polite">{{ status }}</p>
</div>
</template>Installation
npx newtui@latest add pin-inputnpx shadcn@latest add @newtui/pin-inputnpx shadcn-vue@latest add @newtui/pin-inputpnpm dlx newtui@latest add pin-inputpnpm dlx shadcn@latest add @newtui/pin-inputpnpm dlx shadcn-vue@latest add @newtui/pin-inputyarn dlx newtui@latest add pin-inputyarn dlx shadcn@latest add @newtui/pin-inputyarn dlx shadcn-vue@latest add @newtui/pin-inputbunx newtui@latest add pin-inputbunx shadcn@latest add @newtui/pin-inputbunx shadcn-vue@latest add @newtui/pin-inputdeno run -A npm:newtui@latest add pin-inputdeno run -A npm:shadcn@latest add @newtui/pin-inputdeno run -A npm:shadcn-vue@latest add @newtui/pin-inputvlx newtui@latest add pin-inputvlx shadcn@latest add @newtui/pin-inputvlx shadcn-vue@latest add @newtui/pin-inputvp dlx newtui@latest add pin-inputvp dlx shadcn@latest add @newtui/pin-inputvp dlx shadcn-vue@latest add @newtui/pin-inputnubx newtui@latest add pin-inputnubx shadcn@latest add @newtui/pin-inputnubx shadcn-vue@latest add @newtui/pin-inputnlx newtui@latest add pin-inputnlx shadcn@latest add @newtui/pin-inputnlx shadcn-vue@latest add @newtui/pin-inputupx newtui@latest add pin-inputupx shadcn@latest add @newtui/pin-inputupx shadcn-vue@latest add @newtui/pin-input- newtui
- shadcn
- npm
- pnpm
- yarn
- bun
- deno
- vlt
- vp
- nub
- ni
- upm
The shadcn CLI needs the @newtui registry in your components.json. Set it up.
Copy the source into your project
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
export interface PinInputProps extends Omit<
React.HTMLAttributes<HTMLDivElement>,
"onChange" | "defaultValue"
> {
/** How many characters the code has. */
length?: number
/** Controlled code. Leave undefined to let the component own it. */
value?: string
defaultValue?: string
onValueChange?: (value: string) => void
/** Called once, with the code, when the last box is filled. */
onComplete?: (value: string) => void
/** `numeric` accepts digits only; `alphanumeric` also takes letters. */
type?: "numeric" | "alphanumeric"
/** Draw every character as a dot, for a code that is a secret. */
mask?: boolean
/** A separator after every this-many boxes. `0` draws none. */
groupSize?: number
disabled?: boolean
invalid?: boolean
/** Accessible name for the group of boxes. */
label?: string
/** Builds the accessible name of each box. */
formatCellLabel?: (state: PinInputCellLabelState) => string
/** Posts the code with a form, through a hidden input. */
name?: string
}
/** What the accessible name of one box is built from. */
export interface PinInputCellLabelState {
/** The place of the box, from 1. */
position: number
length: number
type: "numeric" | "alphanumeric"
}
/** The English default: `Digit 2 of 6`. Pass `formatCellLabel` to translate it. */
export function defaultPinInputCellLabel({
position,
length,
type,
}: PinInputCellLabelState): string {
return `${type === "numeric" ? "Digit" : "Character"} ${position} of ${length}`
}
/* Global, so `match` returns every accepted character and drops the rest. */
const ACCEPT = {
numeric: /\d/g,
alphanumeric: /[a-z0-9]/gi,
} as const
/** Where a navigation key sends focus, or `undefined` for any other key. */
function moveFor(
key: string,
index: number,
forward: number,
length: number
): number | undefined {
switch (key) {
case "ArrowLeft":
return index - forward
case "ArrowRight":
return index + forward
case "Home":
return 0
case "End":
return length - 1
default:
return undefined
}
}
/*
* A short code, one character to a box. Each box is its own `<input>`, so a
* screen reader can say which one it is on; the first carries
* `one-time-code`, so a code from a text message fills all of them. The value
* is one string with no gaps: a character typed past the end lands in the
* first empty box.
*/
const PinInput = React.forwardRef<HTMLDivElement, PinInputProps>(
(
{
className,
length = 6,
value,
defaultValue = "",
onValueChange,
onComplete,
type = "numeric",
mask = false,
groupSize = 0,
disabled = false,
invalid = false,
label = "Verification code",
formatCellLabel = defaultPinInputCellLabel,
name,
...props
},
ref
) => {
const [internal, setInternal] = React.useState(defaultValue)
const isControlled = value !== undefined
const code = (isControlled ? value : internal).slice(0, length)
const cells = React.useRef<(HTMLInputElement | null)[]>([])
const focus = (index: number) => {
const cell = cells.current[Math.max(0, Math.min(length - 1, index))]
cell?.focus()
cell?.select()
}
const commit = (next: string) => {
if (!isControlled) setInternal(next)
onValueChange?.(next)
if (next.length === length && next !== code) onComplete?.(next)
}
const handleChange = (index: number, raw: string) => {
const existing = code[index] ?? ""
/* With the box's own character still in it, only the rest is new. */
const typed =
existing !== "" && raw.length > 1 && raw.startsWith(existing)
? raw.slice(existing.length)
: raw
const chars = typed.match(ACCEPT[type]) ?? []
if (chars.length === 0) {
if (raw === "") commit(code.slice(0, index) + code.slice(index + 1))
return
}
const at = Math.min(index, code.length)
const next = (
code.slice(0, at) +
chars.join("") +
code.slice(at + chars.length)
).slice(0, length)
commit(next)
focus(at + chars.length)
}
/*
* A paste is handled on its own event. Read from the input's value it
* cannot be told apart from typing, and a pasted code that begins with
* the box's current character would lose that character.
*/
const handlePaste = (
index: number,
event: React.ClipboardEvent<HTMLInputElement>
) => {
event.preventDefault()
const chars =
event.clipboardData.getData("text").match(ACCEPT[type]) ?? []
if (chars.length === 0) return
const at = Math.min(index, code.length)
commit(
(
code.slice(0, at) +
chars.join("") +
code.slice(at + chars.length)
).slice(0, length)
)
focus(at + chars.length)
}
const handleKeyDown = (
index: number,
event: React.KeyboardEvent<HTMLInputElement>
) => {
const forward =
getComputedStyle(event.currentTarget).direction === "rtl" ? -1 : 1
const move = moveFor(event.key, index, forward, length)
if (move !== undefined) {
event.preventDefault()
focus(move)
return
}
if (
event.key === "Backspace" &&
(code[index] ?? "") === "" &&
index > 0
) {
event.preventDefault()
commit(code.slice(0, index - 1) + code.slice(index))
focus(index - 1)
}
}
return (
<div
ref={ref}
role="group"
aria-label={label}
data-invalid={invalid || undefined}
className={cn("group/pin inline-flex items-center gap-2", className)}
{...props}
>
{Array.from({ length }, (_, index) => (
<React.Fragment key={index}>
{groupSize > 0 && index > 0 && index % groupSize === 0 ? (
<span
aria-hidden="true"
className="h-0.5 w-2 rounded-full bg-newt-text-muted"
/>
) : null}
<input
ref={(node) => {
cells.current[index] = node
}}
type={mask ? "password" : "text"}
inputMode={type === "numeric" ? "numeric" : "text"}
autoComplete={index === 0 ? "one-time-code" : "off"}
aria-label={formatCellLabel({
position: index + 1,
length,
type,
})}
aria-invalid={invalid || undefined}
disabled={disabled}
value={code[index] ?? ""}
onChange={(event) => handleChange(index, event.target.value)}
onKeyDown={(event) => handleKeyDown(index, event)}
onPaste={(event) => handlePaste(index, event)}
onFocus={(event) => event.target.select()}
className="h-[52px] w-11 rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-input p-0 text-center font-[family-name:var(--newt-font-mono)] text-xl font-semibold text-newt-text-primary caret-newt-brand transition-colors duration-fast ease-newt focus:border-newt-brand focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 group-data-[invalid]/pin:border-newt-danger"
/>
</React.Fragment>
))}
{name === undefined ? null : (
<input type="hidden" name={name} value={code} />
)}
</div>
)
}
)
PinInput.displayName = "PinInput"
export { PinInput }<script setup lang="ts">
import { computed, ref, type HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import { defaultPinInputCellLabel, type PinInputCellLabelState } from "."
/*
* A short code, one character to a box. Each box is its own `<input>`, so a
* screen reader can say which one it is on; the first carries
* `one-time-code`, so a code from a text message fills all of them. The value
* is one string with no gaps: a character typed past the end lands in the
* first empty box.
*/
const props = withDefaults(
defineProps<{
class?: HTMLAttributes["class"]
/** How many characters the code has. */
length?: number
/** `numeric` accepts digits only; `alphanumeric` also takes letters. */
type?: "numeric" | "alphanumeric"
/** Draw every character as a dot, for a code that is a secret. */
mask?: boolean
/** A separator after every this-many boxes. `0` draws none. */
groupSize?: number
disabled?: boolean
invalid?: boolean
/** Accessible name for the group of boxes. */
label?: string
/** Builds the accessible name of each box. */
formatCellLabel?: (state: PinInputCellLabelState) => string
/** Posts the code with a form, through a hidden input. */
name?: string
}>(),
{
length: 6,
type: "numeric",
mask: false,
groupSize: 0,
disabled: false,
invalid: false,
label: "Verification code",
formatCellLabel: defaultPinInputCellLabel,
}
)
const emit = defineEmits<{
/** Fired once, with the code, when the last box is filled. */
(e: "complete", value: string): void
}>()
const model = defineModel<string>({ default: "" })
/* Global, so `match` returns every accepted character and drops the rest. */
const ACCEPT = {
numeric: /\d/g,
alphanumeric: /[a-z0-9]/gi,
} as const
/** Where a navigation key sends focus, or `undefined` for any other key. */
function moveFor(
key: string,
index: number,
forward: number
): number | undefined {
switch (key) {
case "ArrowLeft":
return index - forward
case "ArrowRight":
return index + forward
case "Home":
return 0
case "End":
return props.length - 1
default:
return undefined
}
}
const code = computed(() => model.value.slice(0, props.length))
const cells = ref<HTMLInputElement[]>([])
function focus(index: number) {
const cell = cells.value[Math.max(0, Math.min(props.length - 1, index))]
cell?.focus()
cell?.select()
}
function commit(next: string) {
const previous = code.value
model.value = next
if (next.length === props.length && next !== previous) emit("complete", next)
}
function onInput(index: number, event: Event) {
if (!(event.target instanceof HTMLInputElement)) return
const raw = event.target.value
const existing = code.value[index] ?? ""
/* With the box's own character still in it, only the rest is new. */
const typed =
existing !== "" && raw.length > 1 && raw.startsWith(existing)
? raw.slice(existing.length)
: raw
const chars = typed.match(ACCEPT[props.type]) ?? []
if (chars.length === 0) {
if (raw === "") {
commit(code.value.slice(0, index) + code.value.slice(index + 1))
} else {
/* Rejected input: put the box back to what the value says. */
event.target.value = existing
}
return
}
const at = Math.min(index, code.value.length)
const next = (
code.value.slice(0, at) +
chars.join("") +
code.value.slice(at + chars.length)
).slice(0, props.length)
commit(next)
event.target.value = next[index] ?? ""
focus(at + chars.length)
}
/*
* A paste is handled on its own event. Read from the input's value it cannot
* be told apart from typing, and a pasted code that begins with the box's
* current character would lose that character.
*/
function onPaste(index: number, event: ClipboardEvent) {
event.preventDefault()
const chars =
event.clipboardData?.getData("text").match(ACCEPT[props.type]) ?? []
if (chars.length === 0) return
const at = Math.min(index, code.value.length)
commit(
(
code.value.slice(0, at) +
chars.join("") +
code.value.slice(at + chars.length)
).slice(0, props.length)
)
focus(at + chars.length)
}
function onKeydown(index: number, event: KeyboardEvent) {
if (!(event.target instanceof HTMLInputElement)) return
const forward = getComputedStyle(event.target).direction === "rtl" ? -1 : 1
const move = moveFor(event.key, index, forward)
if (move !== undefined) {
event.preventDefault()
focus(move)
return
}
if (
event.key === "Backspace" &&
(code.value[index] ?? "") === "" &&
index > 0
) {
event.preventDefault()
commit(code.value.slice(0, index - 1) + code.value.slice(index))
focus(index - 1)
}
}
function onFocus(event: FocusEvent) {
if (event.target instanceof HTMLInputElement) event.target.select()
}
</script>
<template>
<div
role="group"
:aria-label="props.label"
:data-invalid="props.invalid ? true : undefined"
:class="cn('group/pin inline-flex items-center gap-2', props.class)"
>
<template v-for="index in props.length" :key="index">
<span
v-if="
props.groupSize > 0 &&
index > 1 &&
(index - 1) % props.groupSize === 0
"
aria-hidden="true"
class="h-0.5 w-2 rounded-full bg-newt-text-muted"
/>
<input
ref="cells"
:type="props.mask ? 'password' : 'text'"
:inputmode="props.type === 'numeric' ? 'numeric' : 'text'"
:autocomplete="index === 1 ? 'one-time-code' : 'off'"
:aria-label="
props.formatCellLabel({
position: index,
length: props.length,
type: props.type,
})
"
:aria-invalid="props.invalid ? true : undefined"
:disabled="props.disabled"
:value="code[index - 1] ?? ''"
class="h-[52px] w-11 rounded-[var(--newt-radius-sm)] border border-newt-border bg-newt-bg-input p-0 text-center font-[family-name:var(--newt-font-mono)] text-xl font-semibold text-newt-text-primary caret-newt-brand transition-colors duration-fast ease-newt focus:border-newt-brand focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 group-data-[invalid]/pin:border-newt-danger"
@input="onInput(index - 1, $event)"
@keydown="onKeydown(index - 1, $event)"
@paste="onPaste(index - 1, $event)"
@focus="onFocus"
/>
</template>
<input
v-if="props.name !== undefined"
type="hidden"
:name="props.name"
:value="code"
/>
</div>
</template>export { default as PinInput } from "./PinInput.vue"
/** What the accessible name of one box is built from. */
export interface PinInputCellLabelState {
/** The place of the box, from 1. */
position: number
length: number
type: "numeric" | "alphanumeric"
}
/** The English default: `Digit 2 of 6`. Pass `formatCellLabel` to translate it. */
export function defaultPinInputCellLabel({
position,
length,
type,
}: PinInputCellLabelState): string {
return `${type === "numeric" ? "Digit" : "Character"} ${position} of ${length}`
}Update the import paths
The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.
No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Pin Input to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.
No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Pin Input to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.
Usage
import { PinInput } from "@/components/ui/pin-input"
export function Example() {
return <PinInput />
}<script setup lang="ts">
import { PinInput } from "@/components/ui/pin-input"
</script>
<template>
<PinInput />
</template>Examples
Masked
mask draws every character as a dot, for a PIN that should not be read over a shoulder. length sets the number of boxes.
newt-pinimport { PinInput } from "@/registry/bases/newt/ui/pin-input"
export default function PinInputMaskDemo() {
return (
<div className="flex flex-col items-center gap-3">
<PinInput label="Parental PIN" length={4} defaultValue="27" mask />
<p className="text-xs text-newt-text-muted">
Enter the 4-digit PIN to change these settings
</p>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import { PinInput } from "~~/registry/bases/newt/ui/pin-input"
const pin = ref("27")
</script>
<template>
<div class="flex flex-col items-center gap-3">
<PinInput v-model="pin" label="Parental PIN" :length="4" mask />
<p class="text-xs text-newt-text-muted">
Enter the 4-digit PIN to change these settings
</p>
</div>
</template>Alphanumeric
type="alphanumeric" accepts letters as well as digits, and groupSize draws a separator after every four boxes so a long backup code is easier to copy.
newt-pin"use client"
import * as React from "react"
import { PinInput } from "@/registry/bases/newt/ui/pin-input"
export default function PinInputAlphanumericDemo() {
const [code, setCode] = React.useState("k7qd")
return (
<div className="flex flex-col items-center gap-3">
<PinInput
label="Backup code"
type="alphanumeric"
length={8}
groupSize={4}
value={code}
onValueChange={setCode}
/>
<p className="text-xs text-newt-text-muted" aria-live="polite">
{code.length} of 8 characters
</p>
</div>
)
}<script setup lang="ts">
import { ref } from "vue"
import { PinInput } from "~~/registry/bases/newt/ui/pin-input"
const code = ref("k7qd")
</script>
<template>
<div class="flex flex-col items-center gap-3">
<PinInput
v-model="code"
label="Backup code"
type="alphanumeric"
:length="8"
:group-size="4"
/>
<p class="text-xs text-newt-text-muted" aria-live="polite">
{{ code.length }} of 8 characters
</p>
</div>
</template>Invalid
invalid turns every box’s border to the danger colour. Pair it with an error message, and clear it as soon as the code changes: edit the last two digits to 16 to see it pass.
newt-pin"use client"
import * as React from "react"
import { FieldHelp } from "@/registry/bases/newt/ui/form-fields"
import { PinInput } from "@/registry/bases/newt/ui/pin-input"
const EXPECTED = "204816"
/* The error clears as soon as the code is edited, not on the next submit. */
export default function PinInputInvalidDemo() {
const [code, setCode] = React.useState("204861")
const invalid = code.length === EXPECTED.length && code !== EXPECTED
return (
<div className="flex flex-col items-center gap-3">
<PinInput
label="Two-factor code"
groupSize={3}
value={code}
onValueChange={setCode}
invalid={invalid}
/>
{invalid ? (
<FieldHelp variant="error">
That code did not match. Check it and try again.
</FieldHelp>
) : (
<FieldHelp>Enter the 6-digit code from your authenticator.</FieldHelp>
)}
</div>
)
}<script setup lang="ts">
import { computed, ref } from "vue"
import { FieldHelp } from "~~/registry/bases/newt/ui/form-fields"
import { PinInput } from "~~/registry/bases/newt/ui/pin-input"
const EXPECTED = "204816"
/* The error clears as soon as the code is edited, not on the next submit. */
const code = ref("204861")
const invalid = computed(
() => code.value.length === EXPECTED.length && code.value !== EXPECTED
)
</script>
<template>
<div class="flex flex-col items-center gap-3">
<PinInput
v-model="code"
label="Two-factor code"
:group-size="3"
:invalid="invalid"
/>
<FieldHelp v-if="invalid" variant="error">
That code did not match. Check it and try again.
</FieldHelp>
<FieldHelp v-else>
Enter the 6-digit code from your authenticator.
</FieldHelp>
</div>
</template>API reference
PinInput
value / v-model?string
The code so far. In React, leave it undefined and pass `defaultValue` to let the component own it.
stringonValueChange?(value: string) => void
React only. Called on every change; Vue emits `update:modelValue`.
(value: string) => voidonComplete / @complete?(value: string) => void
Called with the code when the last box is filled, and again each time a complete code is changed to a different one.
(value: string) => voidlength?number
How many characters the code has.
number6type?"numeric" | "alphanumeric"
`numeric` accepts digits only and asks a phone for its number pad.
"numeric" | "alphanumeric""numeric"mask?boolean
Draws every character as a dot.
booleanfalsegroupSize?number
Draws a separator after every this-many boxes. `0` draws none.
number0invalid?boolean
Turns the borders to the danger colour and sets `aria-invalid` on each box.
booleanfalsedisabled?boolean
Stops every box taking input.
booleanfalselabel?string
Accessible name of the group.
string"Verification code"name?string
Adds a hidden input with this name, so the code posts with a form.
stringformatCellLabel?(state: { position, length, type }) => string
Builds the accessible name of each box: `Digit 2 of 6`. `position` counts from 1.
(state: { position, length, type }) => stringdefaultPinInputCellLabelSubmit from the complete callback when the code should be checked as soon as it is whole, and keep a visible button for readers who paste a code and expect to confirm it.
Accessibility
The boxes sit in a role="group" named by label, and each box announces its position (“Digit 2 of 6”). The first box carries autocomplete="one-time-code", which lets a phone offer the code from a text message. Left and Right move between boxes following the reading direction, and Home and End jump to the ends. An error needs words as well as the red border: put the message in a FieldHelp with variant="error".
Each box takes its name from formatCellLabel. Translating labels lists every English default.
Tokens
Pin Input reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-pin.
--newt-border--newt-radius-sm--newt-bg-input--newt-text-primary--newt-font-mono--newt-brand--newt-duration-fast--newt-ease--newt-radius-full--newt-text-muted--newt-danger