OTP 필드
OTP 필드 (OTP Field)
일회용 비밀번호와 인증 코드 입력을 위한 고품질의 비스타일 React OTP 필드 컴포넌트예요.
본문
일회용 비밀번호와 검증 코드 입력을 위한 고품질의 비스타일 React OTP 필드 컴포넌트예요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
const OTP_LENGTH = 6;
export default function ExampleOTPField() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className="flex w-full max-w-80 flex-col items-start gap-1">
<label htmlFor={id} className="text-sm font-bold text-neutral-950 dark:text-white">
Verification code
</label>
<OTPField.Root
id={id}
length={OTP_LENGTH}
aria-describedby={descriptionId}
className="flex w-full gap-2"
>
{Array.from({ length: OTP_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${OTP_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className="m-0 text-sm text-neutral-600 dark:text-neutral-400">
Enter the 6-character code we sent to your device.
</p>
</div>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 20rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Root {
display: flex;
gap: 0.5rem;
width: 100%;
}
.Input {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 2.5rem;
height: 2.5rem;
border-radius: 0;
font-family: inherit;
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
text-align: center;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Description {
margin: 0;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
import styles from './index.module.css';
const OTP_LENGTH = 6;
export default function ExampleOTPField() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className={styles.Field}>
<label htmlFor={id} className={styles.Label}>
Verification code
</label>
<OTPField.Root
id={id}
length={OTP_LENGTH}
aria-describedby={descriptionId}
className={styles.Root}
>
{Array.from({ length: OTP_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className={styles.Input}
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${OTP_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className={styles.Description}>
Enter the 6-character code we sent to your device.
</p>
</div>
);
}
사용 가이드라인 (Usage guidelines)
- 폼 컨트롤에는 접근 가능한 이름(accessible name)이 있어야 해요:
<label>요소나Field컴포넌트로 만들 수 있어요. OTP 필드에 라벨 지정하기와 폼 가이드를 참고하세요.
구조 (Anatomy)
컴포넌트를 임포트하고 파트들을 조립하세요.
import { OTPField } from '@base-ui/react/otp-field';
<OTPField.Root>
<OTPField.Input />
<OTPField.Separator />
</OTPField.Root>;
예시 (Examples)
OTP 필드에 라벨 지정하기
<OTPField.Root>에 id를 전달하고 일치하는 htmlFor를 가진 네이티브 <label>을 사용하세요. 첫
input이 필드 라벨을 사용하게 하고, 나머지 input에는 aria-label을 추가해서 보조 기술이 어떤 슬롯이
포커스됐는지 알려주게 하세요.
선택적으로, 필드와 함께 보조 텍스트를 알려야 한다면 aria-describedby를 추가하세요.
<div>
<label htmlFor="verification-code">Verification code</label>
<OTPField.Root id="verification-code" length={6} aria-describedby="verification-code-description">
<OTPField.Input />
<OTPField.Input aria-label="Character 2 of 6" />
<OTPField.Input aria-label="Character 3 of 6" />
<OTPField.Input aria-label="Character 4 of 6" />
<OTPField.Input aria-label="Character 5 of 6" />
<OTPField.Input aria-label="Character 6 of 6" />
</OTPField.Root>
<p id="verification-code-description">Enter the 6-character code we sent to your device.</p>
</div>
폼 통합 (Form integration)
라벨 연결과 폼 통합을 처리하려면 Field를 사용하세요.
<Form>
<Field.Root name="verificationCode">
<Field.Label>Verification code</Field.Label>
<Field.Description>Enter the 6-character code we sent to your device.</Field.Description>
<OTPField.Root length={6}>
<OTPField.Input />
<OTPField.Input aria-label="Character 2 of 6" />
<OTPField.Input aria-label="Character 3 of 6" />
<OTPField.Input aria-label="Character 4 of 6" />
<OTPField.Input aria-label="Character 5 of 6" />
<OTPField.Input aria-label="Character 6 of 6" />
</OTPField.Root>
</Field.Root>
</Form>
모든 슬롯이 채워졌을 때 소유한 폼을 자동으로 제출하려면 autoSubmit을 전달하세요. 제출 없이 완료에 반응하려면 onValueComplete를 사용하세요.
영숫자 인증 코드 (Alphanumeric verification codes)
문자와 숫자가 섞인 복구, 백업, 초대 코드에는 validationType="alphanumeric"을 사용하세요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
const CODE_LENGTH = 6;
export default function OTPFieldAlphanumericDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className="flex w-full max-w-80 flex-col items-start gap-1">
<label htmlFor={id} className="text-sm font-bold text-neutral-950 dark:text-white">
Recovery code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
validationType="alphanumeric"
aria-describedby={descriptionId}
className="flex w-full gap-2"
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className="m-0 text-sm text-neutral-600 dark:text-neutral-400">
Accept letters and numbers for backup codes such as{' '}
<code className="font-mono">A7C9XZ</code>.
</p>
</div>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 20rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Root {
display: flex;
gap: 0.5rem;
width: 100%;
}
.Input {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 2.5rem;
height: 2.5rem;
border-radius: 0;
font-family: inherit;
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
text-align: center;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Description {
margin: 0;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Code {
font-family:
'Paper Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
'Courier New', monospace;
}
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
import styles from './index.module.css';
const CODE_LENGTH = 6;
export default function OTPFieldAlphanumericDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className={styles.Field}>
<label htmlFor={id} className={styles.Label}>
Recovery code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
validationType="alphanumeric"
aria-describedby={descriptionId}
className={styles.Root}
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className={styles.Input}
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className={styles.Description}>
Accept letters and numbers for backup codes such as{' '}
<span className={styles.Code}>A7C9XZ</span>.
</p>
</div>
);
}
그룹형 레이아웃 (Grouped layouts)
input의 일부를 여러분의 레이아웃 요소로 감싸고, 코드를 123-456 같은 더 작은 시각적 덩어리로
보여주고 싶을 때 <OTPField.Separator>를 사용하세요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
const OTP_LENGTH = 6;
export default function OTPFieldGroupedDemo() {
const id = React.useId();
return (
<div className="flex w-full max-w-80 flex-col items-start gap-1">
<label htmlFor={id} className="text-sm font-bold text-neutral-950 dark:text-white">
Verification code
</label>
<OTPField.Root id={id} length={OTP_LENGTH} className="flex w-full items-center gap-2">
<div className="flex gap-2">
{Array.from({ length: 3 }, (_, index) => (
<OTPField.Input
key={index}
className="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${OTP_LENGTH}`}
/>
))}
</div>
<OTPField.Separator className="h-px w-4 bg-current text-neutral-950 dark:text-white" />
<div className="flex gap-2">
{Array.from({ length: 3 }, (_, index) => (
<OTPField.Input
key={index + 3}
className="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
aria-label={`Character ${index + 4} of ${OTP_LENGTH}`}
/>
))}
</div>
</OTPField.Root>
</div>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 20rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Root {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
}
.Group {
display: flex;
gap: 0.5rem;
}
.Input {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 2.5rem;
height: 2.5rem;
border-radius: 0;
font-family: inherit;
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
text-align: center;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Separator {
width: 1rem;
height: 1px;
background-color: currentColor;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
import styles from './index.module.css';
const OTP_LENGTH = 6;
export default function OTPFieldGroupedDemo() {
const id = React.useId();
return (
<div className={styles.Field}>
<label htmlFor={id} className={styles.Label}>
Verification code
</label>
<OTPField.Root id={id} length={OTP_LENGTH} className={styles.Root}>
<div className={styles.Group}>
{Array.from({ length: 3 }, (_, index) => (
<OTPField.Input
key={index}
className={styles.Input}
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${OTP_LENGTH}`}
/>
))}
</div>
<OTPField.Separator className={styles.Separator} />
<div className={styles.Group}>
{Array.from({ length: 3 }, (_, index) => (
<OTPField.Input
key={index + 3}
className={styles.Input}
aria-label={`Character ${index + 4} of ${OTP_LENGTH}`}
/>
))}
</div>
</OTPField.Root>
</div>
);
}
자리표시자 힌트 (Placeholder hints)
<OTPField.Input>은 실제 input이므로 네이티브 placeholder prop과 CSS가 평소처럼 동작해요. 이
예시는 활성 슬롯이 포커스를 받을 때까지 자리표시자 힌트를 보이게 유지해요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
const CODE_LENGTH = 6;
export default function OTPFieldFocusedPlaceholderDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className="flex w-full max-w-80 flex-col items-start gap-1">
<label htmlFor={id} className="text-sm font-bold text-neutral-950 dark:text-white">
Verification code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
aria-describedby={descriptionId}
className="flex w-full gap-2"
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 placeholder:text-neutral-500 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white focus:placeholder:text-transparent dark:border-white dark:text-white dark:placeholder:text-neutral-400"
placeholder="•"
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className="m-0 text-sm text-neutral-600 dark:text-neutral-400">
Placeholder hints can stay visible until the active slot is focused.
</p>
</div>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 20rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Root {
display: flex;
gap: 0.5rem;
width: 100%;
}
.Input {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 2.5rem;
height: 2.5rem;
border-radius: 0;
font-family: inherit;
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
text-align: center;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&::placeholder {
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
&:focus::placeholder {
color: transparent;
}
}
.Description {
margin: 0;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
import styles from './index.module.css';
const CODE_LENGTH = 6;
export default function OTPFieldFocusedPlaceholderDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className={styles.Field}>
<label htmlFor={id} className={styles.Label}>
Verification code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
aria-describedby={descriptionId}
className={styles.Root}
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className={styles.Input}
placeholder="•"
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className={styles.Description}>
Placeholder hints can stay visible until the active slot is focused.
</p>
</div>
);
}
커스텀 정규화 (Custom normalization)
normalizeValue를 사용해 상태 업데이트 전에 허용된 값을 정규화할 수 있어요. 예를 들어 영숫자
코드를 대문자로 변환할 수 있어요. 이 함수는 validationType 필터링 후에 실행되고, 결과는 다시
validationType으로 필터링돼요. 정규화기가 전체 검증 규칙을 제공해야 한다면 validationType="none"을 사용하세요.
커스텀 규칙은 키보드 힌트용 inputMode와 거부된 문자용 onValueInvalid와 함께 짝지으세요.
데모 (Demo)
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 20rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Root {
display: flex;
gap: 0.5rem;
width: 100%;
}
.Input {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 2.5rem;
height: 2.5rem;
border-radius: 0;
font-family: inherit;
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
text-align: center;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.InputInvalidA {
border-color: oklch(50.5% 0.213 27.518deg);
outline: 2px solid oklch(50.5% 0.213 27.518deg);
outline-offset: -1px;
animation: otp-field-shake-a 180ms ease-in-out;
@media (prefers-color-scheme: dark) {
border-color: oklch(70.4% 0.191 22.216deg);
outline: 2px solid oklch(70.4% 0.191 22.216deg);
}
&:focus {
outline: 2px solid oklch(50.5% 0.213 27.518deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: oklch(70.4% 0.191 22.216deg);
}
}
}
.InputInvalidB {
border-color: oklch(50.5% 0.213 27.518deg);
outline: 2px solid oklch(50.5% 0.213 27.518deg);
outline-offset: -1px;
animation: otp-field-shake-b 180ms ease-in-out;
@media (prefers-color-scheme: dark) {
border-color: oklch(70.4% 0.191 22.216deg);
outline: 2px solid oklch(70.4% 0.191 22.216deg);
}
&:focus {
outline: 2px solid oklch(50.5% 0.213 27.518deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: oklch(70.4% 0.191 22.216deg);
}
}
}
.Description {
margin: 0;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.ScreenReaderOnly {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@keyframes otp-field-shake-a {
0%,
100% {
transform: translateX(0);
}
25% {
transform: translateX(-4px);
}
75% {
transform: translateX(4px);
}
}
@keyframes otp-field-shake-b {
0%,
100% {
transform: translateX(0);
}
25% {
transform: translateX(-4px);
}
75% {
transform: translateX(4px);
}
}
/* index.tsx */
'use client';
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
import { useInvalidFeedback } from './useInvalidFeedback';
import styles from './index.module.css';
const CODE_LENGTH = 6;
function normalizeRecoveryCode(value: string) {
return value.toUpperCase();
}
function getInvalidClassName(invalidPulse: number, evenClassName: string, oddClassName: string) {
if (invalidPulse === 0) {
return '';
}
return invalidPulse % 2 === 0 ? evenClassName : oddClassName;
}
export default function OTPFieldCustomNormalizeDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
const {
activeInvalidIndex,
handleValueChange,
handleValueInvalid,
invalidPulse,
setFocusedIndex,
statusMessage,
} = useInvalidFeedback();
const invalidClassName = getInvalidClassName(
invalidPulse,
styles.InputInvalidB,
styles.InputInvalidA,
);
return (
<div className={styles.Field}>
<label htmlFor={id} className={styles.Label}>
Recovery code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
validationType="alphanumeric"
normalizeValue={normalizeRecoveryCode}
onValueChange={handleValueChange}
onValueInvalid={handleValueInvalid}
aria-describedby={descriptionId}
className={styles.Root}
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className={`${styles.Input} ${activeInvalidIndex === index ? invalidClassName : ''}`.trim()}
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
onFocus={() => {
setFocusedIndex(index);
}}
/>
))}
</OTPField.Root>
<p id={descriptionId} className={styles.Description}>
Letters and digits only. Letters are converted to uppercase.
</p>
<span aria-live="polite" className={styles.ScreenReaderOnly}>
{statusMessage}
</span>
</div>
);
}
/* useInvalidFeedback.ts */
'use client';
import * as React from 'react';
export function useInvalidFeedback() {
const [focusedIndex, setFocusedIndex] = React.useState(0);
const [invalidPulse, setInvalidPulse] = React.useState(0);
const [statusMessage, setStatusMessage] = React.useState('');
const invalidTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const skipClearOnNextValueChangeRef = React.useRef(false);
React.useEffect(() => {
return () => {
if (invalidTimeoutRef.current != null) {
clearTimeout(invalidTimeoutRef.current);
}
};
}, []);
function clearInvalidFeedback() {
if (invalidTimeoutRef.current != null) {
clearTimeout(invalidTimeoutRef.current);
invalidTimeoutRef.current = null;
}
setInvalidPulse(0);
setStatusMessage('');
}
function handleValueChange() {
if (skipClearOnNextValueChangeRef.current) {
skipClearOnNextValueChangeRef.current = false;
return;
}
clearInvalidFeedback();
}
function handleValueInvalid(value: string) {
skipClearOnNextValueChangeRef.current = true;
setInvalidPulse((current) => current + 1);
setStatusMessage(`Unsupported characters were ignored from ${value}.`);
if (invalidTimeoutRef.current != null) {
clearTimeout(invalidTimeoutRef.current);
}
invalidTimeoutRef.current = setTimeout(() => {
invalidTimeoutRef.current = null;
setInvalidPulse(0);
}, 400);
}
return {
activeInvalidIndex: invalidPulse > 0 ? focusedIndex : -1,
invalidPulse,
statusMessage,
setFocusedIndex,
handleValueChange,
handleValueInvalid,
};
}
마스킹 입력 (Masked entry)
입력 중에 코드를 가려야 할 때 mask를 사용하세요.
데모 (Demo)
Tailwind
이 예시는 Tailwind CSS로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
const CODE_LENGTH = 6;
export default function OTPFieldPasswordDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className="flex w-full max-w-80 flex-col items-start gap-1">
<label htmlFor={id} className="text-sm font-bold text-neutral-950 dark:text-white">
Access code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
mask
aria-describedby={descriptionId}
className="flex w-full gap-2"
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className="m-0 h-10 w-10 rounded-none border border-neutral-950 bg-white dark:bg-neutral-950 text-center font-inherit text-base font-normal text-neutral-950 focus:outline-2 focus:-outline-offset-1 focus:outline-neutral-950 dark:focus:outline-white dark:border-white dark:text-white"
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className="m-0 text-sm text-neutral-600 dark:text-neutral-400">
Use <code className="font-mono">mask</code> to obscure the code on shared screens.
</p>
</div>
);
}
CSS Modules
이 예시는 CSS Modules로 컴포넌트를 구현하는 방법을 보여줘요.
/* index.module.css */
.Field {
display: flex;
flex-direction: column;
align-items: start;
gap: 0.25rem;
width: 100%;
max-width: 20rem;
}
.Label {
font-size: 0.875rem;
line-height: 1.25rem;
font-weight: 700;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
color: white;
}
}
.Root {
display: flex;
gap: 0.5rem;
width: 100%;
}
.Input {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 1px solid oklch(14.5% 0 0deg);
width: 2.5rem;
height: 2.5rem;
border-radius: 0;
font-family: inherit;
font-size: 1rem;
line-height: 1.5rem;
font-weight: 400;
text-align: center;
background-color: white;
color: oklch(14.5% 0 0deg);
@media (prefers-color-scheme: dark) {
border: 1px solid white;
background-color: oklch(14.5% 0 0deg);
color: white;
}
&:focus {
outline: 2px solid oklch(14.5% 0 0deg);
outline-offset: -1px;
@media (prefers-color-scheme: dark) {
outline-color: white;
}
}
}
.Description {
margin: 0;
font-size: 0.875rem;
line-height: 1.25rem;
color: oklch(43.9% 0 0deg);
@media (prefers-color-scheme: dark) {
color: oklch(70.8% 0 0deg);
}
}
.Code {
font-family:
'Paper Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
'Courier New', monospace;
}
/* index.tsx */
import * as React from 'react';
import { OTPField } from '@base-ui/react/otp-field';
import styles from './index.module.css';
const CODE_LENGTH = 6;
export default function OTPFieldPasswordDemo() {
const id = React.useId();
const descriptionId = `${id}-description`;
return (
<div className={styles.Field}>
<label htmlFor={id} className={styles.Label}>
Access code
</label>
<OTPField.Root
id={id}
length={CODE_LENGTH}
mask
aria-describedby={descriptionId}
className={styles.Root}
>
{Array.from({ length: CODE_LENGTH }, (_, index) => (
<OTPField.Input
key={index}
className={styles.Input}
aria-label={index === 0 ? undefined : `Character ${index + 1} of ${CODE_LENGTH}`}
/>
))}
</OTPField.Root>
<p id={descriptionId} className={styles.Description}>
Use <span className={styles.Code}>mask</span> to obscure the code on shared screens.
</p>
</div>
);
}
API 레퍼런스 (API reference)
Root
모든 OTP 필드 파트를 그룹화하고 상태를 관리해요.
<div> 요소를 렌더링해요.
Root Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| name | string |
- | 폼이 제출될 때 필드를 식별해요. |
| defaultValue | string |
- | 컴포넌트가 처음 렌더링될 때의 비제어 OTP 값이에요. |
| value | string |
- | OTP 값이에요. |
| onValueChange | ((value: string, eventDetails: OTPField.Root.ChangeEventDetails) => void) |
- | OTP 값이 변경될 때 호출되는 콜백이에요. eventDetails.reason은 변경을 유발한 원인을 나타내요: 'input-change'는 입력 또는 자동 완성, 'input-clear'는 텍스트 입력으로 문자가 제거될 때, 'input-paste'는 붙여넣기 상호작용, 'keyboard'는 값을 변경하는 키보드 상호작용이에요 |
| autoComplete | string |
'one-time-code' |
input autocomplete 속성이에요. 첫 슬롯과 숨겨진 검증 input에 적용돼요. |
| autoSubmit | boolean |
false |
OTP가 완료됐을 때 소유한 폼을 제출할지 여부예요. |
| form | string |
- | 숨겨진 input이 연결되는 form 요소를 지정하는 문자열이에요.
이 문자열의 값은 같은 문서 안의 form 요소의 id와 일치해야 해요. |
| inputMode | 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search' |
- | 슬롯 input과 숨겨진 검증 input에 적용되는 가상 키보드 힌트예요. 내장 검증 모드가 합리적인 기본값을 제공하지만, 필요할 때 덮어쓸 수 있어요. |
| length* | number |
- | OTP 입력 슬롯의 개수예요. root가 값을 제한하고, 완료를 감지하고, 모든 슬롯이 하이드레이션되기 전에 일관된 검증 마크업을 생성하려면 필수예요. |
| mask | boolean |
false |
슬롯 input이 입력된 문자를 마스킹할지 여부예요.
커스텀 input type을 사용하려면 개별 <OTPField.Input> 파트에 type을 직접 전달하세요. |
| normalizeValue | ((value: string) => string) |
- | 공백과 validationType 필터링 후 OTP 값을 정규화하는 함수예요.
OTP Field가 값을 정규화할 때마다(초기/기본값, 제어값, 사용자 편집 포함) 실행돼요. 반환된 값은 다시 validationType으로 필터링된 뒤 length로 제한돼요.
OTP Field는 편집 처리, 상태 저장, 제어·비제어 값 렌더링 동안 같은 값을 여러 번 정규화할 수 있으므로 멱등(idempotent)이어야 해요. 멱등이 아닌
정규화기는 정규화 과정에서 복합적으로 누적될 수 있어요. 입력되거나 붙여넣은 텍스트를 정규화하면서 거부된 문자는 onValueInvalid로 보고돼요. |
| onValueComplete | ((value: string, eventDetails: OTPField.Root.CompleteEventDetails) => void) |
- | OTP 값이 완성되거나, OTP가 이미 완성된 상태에서 완전한 값이 붙여넣어졌을 때 호출되는 콜백 함수예요. 값이 변경되면 내부 값 업데이트가 적용된 뒤 onValueChange보다 나중에 실행돼요. 붙여넣은 완전한 값이 현재 값과 일치하면 onValueChange는 호출되지 않아요. autoSubmit이 활성화되면 소유한 폼이 제출되기 직전에 실행돼요. |
| onValueInvalid | ((value: string, eventDetails: OTPField.Root.InvalidEventDetails) => void) |
- | 입력된 텍스트에 검증이나 정규화로 거부되는 문자가 있어 OTP 값이 업데이트되기 전에 호출되는 콜백이에요. value 인자는 정규화 전의 사용자가 입력한 문자열이에요. |
| validationType | OTPField.Root.ValidationType |
'numeric' |
OTP 값에 적용할 입력 검증 유형이에요. |
| disabled | boolean |
false |
컴포넌트가 사용자 상호작용을 무시할지 여부예요. |
| readOnly | boolean |
false |
사용자가 필드 값을 변경할 수 없게 할지 여부예요. |
| required | boolean |
false |
사용자가 폼을 제출하기 전에 값을 입력해야 하는지 여부예요. |
| id | string |
- | 첫 input 요소의 id예요.
이후 input은 여기서 파생된 id를 사용해요 ({id}-2, {id}-3, ...). |
| className | string | ((state: OTPField.Root.State) => string | undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태를 기반으로 클래스를 반환하는 함수예요. |
| style | React.CSSProperties | ((state: OTPField.Root.State) => React.CSSProperties | undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태를 기반으로 스타일 객체를 반환하는 함수예요. |
| render | ReactElement | ((props: HTMLProps, state: OTPField.Root.State) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
Root Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | OTP 필드가 비활성화됐을 때 존재해요. |
| data-readonly | - | OTP 필드가 읽기 전용일 때 존재해요. |
| data-required | - | OTP 필드가 필수일 때 존재해요. |
| data-valid | - | OTP 필드가 유효 상태일 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-invalid | - | OTP 필드가 무효 상태일 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-dirty | - | OTP 필드의 값이 변경됐을 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-touched | - | OTP 필드가 터치(포커스)됐을 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-complete | - | 모든 슬롯이 채워졌을 때 존재해요. |
| data-filled | - | OTP 필드에 문자가 하나 이상 있을 때 존재해요. |
| data-focused | - | OTP 필드 input 중 하나가 포커스됐을 때 존재해요. |
Root.Props
Root props의 재내보내기(re-export)예요.
Root.State
type OTPFieldRootState = {
/** Whether all slots are filled. */
complete: boolean;
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** The number of OTP input slots. */
length: number;
/** Whether the user should be unable to change the field value. */
readOnly: boolean;
/** Whether the user must enter a value before submitting a form. */
required: boolean;
/** The OTP value. */
value: string;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field has a value. */
filled: boolean;
/** Whether the field is focused. */
focused: boolean;
};
Root.ChangeEventReason
type OTPFieldRootChangeEventReason = 'input-change' | 'input-clear' | 'input-paste' | 'keyboard';
Root.ChangeEventDetails
type OTPFieldRootChangeEventDetails = (
| { reason: 'input-change'; event: InputEvent | Event }
| { reason: 'input-clear'; event: InputEvent | Event | FocusEvent }
| { reason: 'input-paste'; event: ClipboardEvent }
| { reason: 'keyboard'; event: KeyboardEvent }
) & {
/** Cancels Base UI from handling the event. */
cancel: () => void;
/** Allows the event to propagate in cases where Base UI will stop the propagation. */
allowPropagation: () => void;
/** Indicates whether the event has been canceled. */
isCanceled: boolean;
/** Indicates whether the event is allowed to propagate. */
isPropagationAllowed: boolean;
/** The element that triggered the event, if applicable. */
trigger: Element | undefined;
};
Root.CompleteEventDetails
type OTPFieldRootCompleteEventDetails =
| { reason: 'input-change'; event: InputEvent | Event }
| { reason: 'input-paste'; event: ClipboardEvent };
Root.CompleteEventReason
type OTPFieldRootCompleteEventReason = 'input-change' | 'input-paste';
Root.InvalidEventDetails
type OTPFieldRootInvalidEventDetails =
| { reason: 'input-change'; event: InputEvent | Event }
| { reason: 'input-paste'; event: ClipboardEvent };
Root.InvalidEventReason
type OTPFieldRootInvalidEventReason = 'input-change' | 'input-paste';
Root.ValidationType
type OTPFieldRootValidationType = 'numeric' | 'alpha' | 'alphanumeric' | 'none';
Input
개별 OTP 문자 입력이에요.
<input> 요소를 렌더링해요.
Input Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| className | string | ((state: OTPField.Input.State) => string | undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태를 기반으로 클래스를 반환하는 함수예요. |
| style | React.CSSProperties | ((state: OTPField.Input.State) => React.CSSProperties | undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태를 기반으로 스타일 객체를 반환하는 함수예요. |
| render | ReactElement | ((props: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, state: OTPField.Input.State) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
Input Data Attributes:
| Attribute | Type | Description |
|---|---|---|
| data-disabled | - | OTP 필드가 비활성화됐을 때 존재해요. |
| data-readonly | - | OTP 필드가 읽기 전용일 때 존재해요. |
| data-required | - | OTP 필드가 필수일 때 존재해요. |
| data-valid | - | OTP 필드가 유효 상태일 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-invalid | - | OTP 필드가 무효 상태일 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-dirty | - | OTP 필드의 값이 변경됐을 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-touched | - | OTP 필드가 터치(포커스)됐을 때(Field.Root에 감싸졌을 때) 존재해요. |
| data-complete | - | 모든 슬롯이 채워졌을 때 존재해요. |
| data-filled | - | input에 문자가 있을 때 존재해요. |
| data-focused | - | OTP 필드 input 중 하나가 포커스됐을 때 존재해요. |
Input.Props
Input props의 재내보내기(re-export)예요.
Input.State
type OTPFieldInputState = {
/** Whether this input contains a character. */
filled: boolean;
/** The input index. */
index: number;
/** The character rendered in this slot. */
value: string;
/** Whether the component should ignore user interaction. */
disabled: boolean;
/** The number of OTP input slots. */
length: number;
/** Whether the user must enter a value before submitting a form. */
required: boolean;
/** Whether the user should be unable to change the field value. */
readOnly: boolean;
/** Whether all slots are filled. */
complete: boolean;
/** Whether the field has been touched. */
touched: boolean;
/** Whether the field value has changed from its initial value. */
dirty: boolean;
/** Whether the field is valid. */
valid: boolean | null;
/** Whether the field is focused. */
focused: boolean;
};
Separator
화면 읽기 프로그램이 접근할 수 있는 구분 요소예요.
<div> 요소를 렌더링해요.
Separator Props:
| Prop | Type | Default | Description |
|---|---|---|---|
| orientation | Orientation |
'horizontal' |
구분 요소의 방향이에요. |
| className | string | ((state: SeparatorState) => string | undefined) |
- | 요소에 적용되는 CSS 클래스, 또는 컴포넌트 상태를 기반으로 클래스를 반환하는 함수예요. |
| style | React.CSSProperties | ((state: SeparatorState) => React.CSSProperties | undefined) |
- | 요소에 적용되는 스타일, 또는 컴포넌트 상태를 기반으로 스타일 객체를 반환하는 함수예요. |
| render | ReactElement | ((props: HTMLProps, state: SeparatorState) => ReactElement) |
- | 컴포넌트의 HTML 요소를 다른 태그로 대체하거나 다른 컴포넌트와 합성할 수 있게 해줘요. ReactElement 또는 렌더링할 요소를 반환하는 함수를 받아요. |
Separator.Props
Separator props의 재내보내기(re-export)예요.
Separator.State
type OTPFieldSeparatorState = {
/** The orientation of the separator. */
orientation: Orientation;
};
외부 타입 (External Types)
ValidationType
type ValidationType = 'numeric' | 'alpha' | 'alphanumeric' | 'none';
Orientation
type Orientation = 'horizontal' | 'vertical';
Export Groups
OTPField.Root:OTPField.Root,OTPField.Root.State,OTPField.Root.Props,OTPField.Root.ValidationType,OTPField.Root.ChangeEventReason,OTPField.Root.ChangeEventDetails,OTPField.Root.InvalidEventReason,OTPField.Root.InvalidEventDetails,OTPField.Root.CompleteEventReason,OTPField.Root.CompleteEventDetailsOTPField.Input:OTPField.Input,OTPField.Input.State,OTPField.Input.PropsOTPField.Separator:OTPField.Separator,OTPField.Separator.Props,OTPField.Separator.StateDefault:OTPFieldRootProps,OTPFieldRootState,OTPFieldRootChangeEventReason,OTPFieldRootChangeEventDetails,OTPFieldRootInvalidEventReason,OTPFieldRootInvalidEventDetails,OTPFieldRootCompleteEventReason,OTPFieldRootCompleteEventDetails,OTPFieldInputState,OTPFieldInputProps
Canonical Types
Canonical: Alias 매핑 — Canonical의 네임스페이스가 이미 임포트되어 있으면 Canonical을, 아니면 Alias를 사용하세요.
OTPField.Root.State:OTPFieldRootStateOTPField.Root.Props:OTPFieldRootPropsOTPField.Root.ChangeEventReason:OTPFieldRootChangeEventReasonOTPField.Root.ChangeEventDetails:OTPFieldRootChangeEventDetailsOTPField.Root.InvalidEventReason:OTPFieldRootInvalidEventReasonOTPField.Root.InvalidEventDetails:OTPFieldRootInvalidEventDetailsOTPField.Root.CompleteEventReason:OTPFieldRootCompleteEventReasonOTPField.Root.CompleteEventDetails:OTPFieldRootCompleteEventDetailsOTPField.Input.State:OTPFieldInputStateOTPField.Input.Props:OTPFieldInputProps