Skip to content

Commit 3c7e93e

Browse files
author
ugogo
committed
add guards when ref.current is undefined
1 parent f6941e3 commit 3c7e93e

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

src/index.tsx

+10-6
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ const ReactInputVerificationCode = ({
3434

3535
const isCodeRegex = new RegExp(`^[0-9]{${length}}$`);
3636

37-
const getItem = (index: number) => itemsRef[index].current!;
38-
const focusItem = (index: number): void => getItem(index).focus();
39-
const blurItem = (index: number): void => getItem(index).blur();
37+
const getItem = (index: number) => itemsRef[index]?.current;
38+
const focusItem = (index: number): void => getItem(index)?.focus();
39+
const blurItem = (index: number): void => getItem(index)?.blur();
4040

4141
const onItemFocus = (index: number) => () => {
4242
setActiveIndex(index);
@@ -48,6 +48,9 @@ const ReactInputVerificationCode = ({
4848
const nextIndex = activeIndex + 1;
4949
const prevIndex = activeIndex - 1;
5050

51+
const codeInput = codeInputRef.current;
52+
const currentItem = getItem(activeIndex);
53+
5154
const isLast = nextIndex === length;
5255
const isDeleting =
5356
keyCode === KEY_CODE.DELETE || keyCode === KEY_CODE.BACKSPACE;
@@ -75,7 +78,7 @@ const ReactInputVerificationCode = ({
7578

7679
// reset the current value
7780
// and set the new one
78-
if (codeInputRef.current) codeInputRef.current.value = '';
81+
if (codeInput) codeInput.value = '';
7982
newValue[activeIndex] = key;
8083
setValue(newValue);
8184

@@ -85,8 +88,9 @@ const ReactInputVerificationCode = ({
8588
return;
8689
}
8790

88-
if (codeInputRef.current) codeInputRef.current.blur();
89-
getItem(activeIndex).blur();
91+
if (codeInput) codeInput.blur();
92+
if (currentItem) currentItem.blur();
93+
9094
setActiveIndex(-1);
9195
};
9296

0 commit comments

Comments
 (0)