Skip to content
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
8 changes: 8 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ const OTPInput = ({
skipDefaultStyles = false,
}: OTPInputProps) => {
const [activeInput, setActiveInput] = React.useState(0);
const latestActiveInput = React.useRef(activeInput);
latestActiveInput.current = activeInput;

const inputRefs = React.useRef<Array<HTMLInputElement | null>>([]);

const getOTPValue = () => (value ? value.toString().split('') : []);
Expand Down Expand Up @@ -195,6 +198,11 @@ const OTPInput = ({
const changeCodeAtFocus = (value: string) => {
const otp = getOTPValue();
otp[activeInput] = value[0];
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that value[0] is not undefined before assigning it to otp[activeInput] to prevent potential runtime errors.

if (value[0] !== undefined) {
    otp[activeInput] = value[0];
}

const lastValueIndex = otp.join('').length - 1;
if (lastValueIndex < activeInput) {
setActiveInput(lastValueIndex);
latestActiveInput.current = lastValueIndex;
}
handleOTPChange(otp);
};

Expand Down