Skip to content
This repository was archived by the owner on Nov 3, 2024. It is now read-only.

feat: added arrow key traversal #59

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ const AuthCode = forwardRef<AuthCodeRef, AuthCodeProps>(
useEffect(() => {
if (autoFocus) {
inputsRef.current[0].focus();
setFocusPosition(0)
}
}, []);

Expand Down Expand Up @@ -140,18 +141,30 @@ const AuthCode = forwardRef<AuthCodeRef, AuthCodeProps>(
const handleOnKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
const { key } = e;
const target = e.target as HTMLInputElement;
if (key === 'Backspace') {
if (target.value === '') {
if (target.previousElementSibling !== null) {
const t = target.previousElementSibling as HTMLInputElement;
t.value = '';
t.focus();
e.preventDefault();

switch (key) {
case 'Backspace': {
if (target.value === '') {
if (target.previousElementSibling !== null) {
const t = target.previousElementSibling as HTMLInputElement;
t.value = '';
t.focus();
e.preventDefault();
}
} else {
target.value = '';
}
} else {
target.value = '';
sendResult();
}

// Handle left / right traversal
case 'ArrowLeft': {
target.previousElementSibling?.focus()
}

case 'ArrowRight': {
target.nextElementSibling?.focus()
}
sendResult();
}
};

Expand Down