React 앱에서 OTP(One-Time Password) 입력 UI를 구현하는 방법에 대해 알아보겠습니다. OTP 입력은 보안 인증에 자주 사용되며, 사용자 경험을 고려한 UI가 중요합니다.
1. OTP 입력 UI 설계하기
일반적으로 OTP는 4자리 또는 6자리 숫자로 구성됩니다. 각 숫자를 별도의 입력란에 입력받아 자동으로 포커스가 이동하는 인터페이스가 사용자 편의성을 높입니다.
2. React 컴포넌트 구현 예제
아래는 6자리 OTP 입력 UI의 기본 구현 예제입니다. 각 입력란은 숫자만 받도록 제한하며, 입력 시 다음 input으로 자동 포커스가 이동합니다.
import React, { useState, useRef } from 'react';
const OTPInput = ({ length = 6, onChangeOTP }) => {
const [otp, setOtp] = useState(new Array(length).fill(''));
const inputsRef = useRef([]);
const handleChange = (element, index) => {
const val = element.value.replace(/[^0-9]/g, ''); // 숫자만 허용
if (!val) return;
const newOtp = [...otp];
newOtp[index] = val[0];
setOtp(newOtp);
if (index < length - 1) {
inputsRef.current[index + 1].focus();
}
if (onChangeOTP) {
onChangeOTP(newOtp.join(''));
}
};
const handleKeyDown = (e, index) => {
if (e.key === 'Backspace' && !otp[index] && index !== 0) {
const newOtp = [...otp];
newOtp[index - 1] = '';
setOtp(newOtp);
inputsRef.current[index - 1].focus();
}
};
return (
<div style={{ display: 'flex', gap: '8px' }}>
{otp.map((data, index) => (
<input
key={index}
type="text"
maxLength={1}
value={data}
onChange={(e) => handleChange(e.target, index)}
onKeyDown={(e) => handleKeyDown(e, index)}
ref={el => (inputsRef.current[index] = el)}
style={{
width: '40px',
height: '40px',
fontSize: '24px',
textAlign: 'center',
border: '1px solid #ccc',
borderRadius: '4px'
}}
/>
))}
</div>
);
};
export default OTPInput;
3. 사용 시 주의 사항
- 모바일 및 데스크탑 모두에서 키보드 접근성과 포커스 이동이 원활한지 꼭 테스트하세요.
- 보안을 위해 입력값은 서버 단에서 검증해야 하며, 클라이언트에서는 UI만 담당합니다.
- 사용자 편의를 위해 자동 완성 속성을 활용할 수도 있습니다 (예: autocomplete="one-time-code").
'React' 카테고리의 다른 글
| React 앱에서 브라우저 Wake Lock API 활용하기 (0) | 2026.07.26 |
|---|---|
| React에서 OpenAPI 기반 API 클라이언트 자동 생성하기 (1) | 2026.07.26 |
| React에서 Canvas 기반 이미지 크롭 편집기 구현하기 (0) | 2026.07.24 |
| React 앱에서 Electron 연동하여 데스크톱 애플리케이션 개발하기 (0) | 2026.07.23 |
| React에서 Resize Observer API로 반응형 컴포넌트 만들기 (0) | 2026.07.23 |