PIN Input 문서
PIN Input은 한 글자씩 입력하는 칸을 이어 붙여 시퀀스를 받는 컴포넌트예요. OTP(일회용 비밀번호), 2FA(2단계 인증), MFA(다중 인증) 입력처럼 짧은 코드를 받을 때 아주 유용해요.
출처: 문서
본문
아래 예시는 6자리 숫자 PIN을 받는 모습이에요. 셀을 두 덩어리로 나누고 가운데에 구분선을 넣어 시각적으로도 보기 좋게 꾸몄어요.
<script lang="ts">
import {
PinInput,
REGEXP_ONLY_DIGITS,
type PinInputRootSnippetProps
} from "bits-ui";
import { toast } from "svelte-sonner";
import cn from "clsx";
let value = $state("");
type CellProps = PinInputRootSnippetProps["cells"][0];
function onComplete() {
toast.success(`Completed with value ${value}`);
value = "";
}
</script>
<PinInput.Root
bind:value
class="group/pininput text-foreground has-disabled:opacity-30 flex items-center"
maxlength={6}
{onComplete}
pattern={REGEXP_ONLY_DIGITS}
>
{#snippet children({ cells })}
<div class="flex">
{#each cells.slice(0, 3) as cell, i (i)}
{@render Cell(cell)}
{/each}
</div>
<div class="flex w-10 items-center justify-center">
<div class="bg-border h-1 w-3 rounded-full"></div>
</div>
<div class="flex">
{#each cells.slice(3, 6) as cell, i (i)}
{@render Cell(cell)}
{/each}
</div>
{/snippet}
</PinInput.Root>
{#snippet Cell(cell: CellProps)}
<PinInput.Cell
{cell}
class={cn(
// Custom class to override global focus styles
"focus-override",
"relative h-14 w-10 text-[2rem]",
"flex items-center justify-center",
"transition-all duration-75",
"border-foreground/20 border-y border-r first:rounded-l-md first:border-l last:rounded-r-md",
"text-foreground group-focus-within/pininput:border-foreground/40 group-hover/pininput:border-foreground/40",
"outline-0",
"data-active:outline-1 data-active:outline-white"
)}
>
{#if cell.char !== null}
<div>
{cell.char}
</div>
{/if}
{#if cell.hasFakeCaret}
<div
class="animate-caret-blink pointer-events-none absolute inset-0 flex items-center justify-center"
>
<div class="h-8 w-px bg-white"></div>
</div>
{/if}
</PinInput.Cell>
{/snippet}
개요 (Overview)
PIN Input 컴포넌트는 OTP(One-Time Password), 2FA(Two-Factor Authentication), MFA(Multi-Factor Authentication) 입력 필드를 위한 커스터마이즈 가능한 솔루션을 제공해요. 이런 용도에 맞는 기본 HTML 요소가 없다 보니, 개발자들은 보통 단순한 입력 필드나 직접 만든 구현에 의존하곤 해요. 이 컴포넌트는 그 대안으로 튼튼하고 접근성 좋으며 유연한 선택지를 줘요.
크레딧 (Credits)
이 컴포넌트는 Guilherme Rodz 님의 Input OTP 작업을 바탕으로 만들어졌어요. 그 작업이 없었다면 이 컴포넌트도 존재할 수 없었을 거예요.
핵심 기능 (Key Features)
- 보이지 않는 입력 기법 (Invisible Input Technique): 보이지 않는 입력 요소를 활용해 폼 제출과 브라우저 자동 완성 기능과 자연스럽게 연동돼요.
- 커스터마이즈 가능한 외형 (Customizable Appearance): 핵심 기능은 유지하면서 디자인을 자유롭게 바꿀 수 있어요.
- 접근성 (Accessibility): 키보드 탐색과 스크린 리더 호환성을 보장해요.
- 유연한 구성 (Flexible Configuration): 다양한 PIN 길이와 입력 타입(숫자, 영숫자)을 지원해요.
구조 (Architecture)
- 루트 컨테이너 (Root Container): 상대 위치(relatively positioned)를 가진 루트 요소로, 컴포넌트 전체를 감싸요.
- 보이지 않는 입력 (Invisible Input): 실제 값을 관리하고 브라우저 내장 기능과 상호작용하는 숨겨진 입력 필드예요.
- 시각적 셀 (Visual Cells): PIN의 각 문자를 나타내는 커스터마이즈 가능한 요소로, 보이지 않는 입력과 형제(sibling)로 렌더링돼요.
이 구조 덕분에 사용자 경험은 매끄럽고, 개발자에게는 시각적 표현을 완전히 제어할 수 있는 자유가 주어져요.
구조 (Structure)
PIN Input의 기본 구조는 PinInput.Root가 셀 목록을 cells로 내려 주고, 그 안에서 PinInput.Cell을 반복해 그리는 방식이에요.
<script lang="ts">
import { PinInput } from "bits-ui";
</script>
<PinInput.Root maxlength={6}>
{#snippet children({ cells })}
{#each cells as cell}
<PinInput.Cell {cell} />
{/each}
{/snippet}
</PinInput.Root>
값 상태 다루기 (Managing Value State)
이번 절에서는 컴포넌트의 value 상태를 어떻게 다루는지 설명할게요.
양방향 바인딩 (Two-Way Binding)
간단하고 자동으로 상태를 동기화하고 싶다면 bind:value를 사용해요.
<script lang="ts">
import { PinInput } from "bits-ui";
let myValue = $state("");
</script>
<button onclick={() => (myValue = "123456")}> Set value to 123456 </button>
<PinInput.Root bind:value={myValue}>
<!-- -->
</PinInput.Root>
완전 제어 (Fully Controlled)
상태의 읽기와 쓰기를 모두 직접 제어하고 싶다면 Function Binding을 사용해요.
<script lang="ts">
import { PinInput } from "bits-ui";
let myValue = $state("");
function getValue() {
return myValue;
}
function setValue(newValue: string) {
myValue = newValue;
}
</script>
<PinInput.Root bind:value={getValue, setValue}>
<!-- ... -->
</PinInput.Root>
붙여넣기 변환 (Paste Transformation)
pasteTransformer prop을 사용하면 붙여넣은 텍스트를 정리하거나 변환할 수 있어요. 예를 들어 하이픈처럼 입력에 들어가면 안 되는 문자를 제거할 때 유용해요. 이 함수는 정리된 텍스트를 반환해야 하고, 그 값이 입력의 새 값으로 사용돼요.
<script lang="ts">
import { PinInput } from "bits-ui";
</script>
<PinInput.Root pasteTransformer={(text) => text.replace(/-/g, "")}>
<!-- ... -->
</PinInput.Root>
HTML 폼 (HTML Forms)
PinInput.Root 컴포넌트는 HTML 폼과 원활하게 동작하도록 설계됐어요. PinInput.Root에 name prop을 전달하기만 하면 입력 값이 폼과 함께 제출돼요.
입력 완료 시 제출 (Submit On Complete)
입력이 완성되면 폼을 제출하고 싶다면 onComplete prop을 사용할 수 있어요.
<script lang="ts">
import { PinInput } from "bits-ui";
let form = $state<HTMLFormElement>(null!);
</script>
<form method="POST" bind:this={form}>
<PinInput.Root name="mfaCode" onComplete={() => form.submit()}>
<!-- ... -->
</PinInput.Root>
</form>
패턴 (Patterns)
pattern prop을 사용하면 입력이나 붙여넣기로 들어갈 수 있는 문자를 제한할 수 있어요.
참고! (Note!)
클라이언트 측 유효성 검사는 서버 측 유효성 검사를 대체할 수 없어요. 더 나은 사용자 경험을 위해 서버 측 유효성 검사와 함께 사용하세요.
Bits UI는 애플리케이션에서 import 해서 쓸 수 있는 몇 가지 공용 패턴을 제공해요.
REGEXP_ONLY_DIGITS- 숫자만 입력할 수 있어요.REGEXP_ONLY_CHARS- 문자만 입력할 수 있어요.REGEXP_ONLY_DIGITS_AND_CHARS- 숫자와 문자만 입력할 수 있어요.
<script lang="ts">
import { PinInput, REGEXP_ONLY_DIGITS } from "bits-ui";
</script>
<PinInput.Root pattern={REGEXP_ONLY_DIGITS}>
<!-- ... -->
</PinInput.Root>
API Reference
PINInput.Root
The pin input container component.
| Property | Type | Description | Details |
|---|---|---|---|
value $bindable |
string |
The value of the input.Default: —— undefined |
|
onValueChange |
function - (value: string) => void |
A callback function that is called when the value of the input changes.Default: —— undefined |
|
disabled |
boolean |
Whether or not the pin input is disabled.Default: false |
|
textalign |
enum - 'left' | 'center' | 'right' |
Where is the text located within the input. Affects click-holding or long-press behaviorDefault: 'left' |
|
maxlength |
number |
The maximum length of the pin input.Default: 6 |
|
onComplete |
function - (...args: any[]) => void |
A callback function that is called when the input is completely filled.Default: —— undefined |
|
pasteTransformer |
function - (text: string) => string |
A callback function that is called when the user pastes text into the input. It receives the pasted text as an argument and should return the sanitized text. Useful for cleaning up pasted text, like removing hyphens or other characters that should not make it into the input.Default: —— undefined |
|
inputId |
string |
Optionally provide an ID to apply to the hidden input element.Default: —— undefined |
|
inputRef $bindable |
HTMLInputElement |
The hidden `` element that holds the OTP value. Bind to this to call focus(), read the selection, etc.Default: null |
|
pushPasswordManagerStrategy |
enum - 'increase-width' | 'none' |
Enabled by default, it's an optional strategy for detecting Password Managers in the page and then shifting their badges to the right side, outside the input.Default: —— undefined |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet - type PinInputCell = { /** The character displayed in the cell. */ char: string | null | undefined /** Whether the cell is active. */ isActive: boolean /** Whether the cell has a fake caret. */ hasFakeCaret: boolean } type SnippetProps = { cells: PinInputCell[] } |
The children content to render.Default: —— undefined |
|
child |
Snippet - type PinInputCell = { /** The character displayed in the cell. */ char: string | null | undefined /** Whether the cell is active. */ isActive: boolean /** Whether the cell has a fake caret. */ hasFakeCaret: boolean } type SnippetProps = { cells: PinInputCell[] props: Record<string, unknown> } |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-pin-input-root |
'' |
Present on the root element. |
PINInput.Cell
A single cell of the pin input.
| Property | Type | Description | Details |
|---|---|---|---|
cell |
object - type Cell = { /** The character displayed in the cell. */ char: string | null | undefined /** Whether the cell is active. */ isActive: boolean /** Whether the cell has a fake caret. */ hasFakeCaret: boolean } |
The cell object provided by the cells snippet prop from the PinInput.Root component.Default: —— undefined |
|
ref $bindable |
HTMLDivElement |
The underlying DOM element being rendered. You can bind to this to get a reference to the element.Default: null |
|
children |
Snippet |
The children content to render.Default: —— undefined |
|
child |
Snippet - type SnippetProps = { props: Record<string, unknown>; }; |
Use render delegation to render your own element. See Child Snippet docs for more information.Default: —— undefined |
| Data Attribute | Value | Description | Details |
|---|---|---|---|
data-active |
'' |
Present when the cell is active. | |
data-inactive |
'' |
Present when the cell is inactive. | |
data-pin-input-cell |
'' |
Present on the cell element. |
더 알아보기 (Learn more)
PIN Input은 bind:value나 함수 바인딩으로 값을 제어하고, pattern과 pasteTransformer로 입력 내용을 다듬을 수 있어요. 다중 인증(MFA) 흐름이 필요하다면 비밀번호 입력을 처리하는 Field나 Toggle Group 같은 폼 컴포넌트와 함께 조합해 사용할 수 있어요.