'use client'; import React, { createRef, useEffect, useRef, useState } from 'react' type Props = { htmlFor: string; labelText?: React.ReactNode; value?: string; onChange: (e: React.ChangeEvent) => void; maxLength?: number; className?: string; } & Omit, "id">; function OTPInputField({ onChange, maxLength = 6, htmlFor, labelText, className, autoFocus, value = '', ...restProps }: Props) { const values = value?.toString().split('').slice(0, maxLength); const inputRefs = useRef(Array.from({ length: maxLength }, () => createRef())); const [prevLength, setPrevLength] = useState(0); useEffect(() => { const valLength = values.length; const focusIndex = valLength < prevLength ? Math.max(0, valLength) : Math.min(valLength, maxLength - 1); inputRefs.current[focusIndex]?.current?.focus(); setPrevLength(valLength); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); const keyDown = (e: React.KeyboardEvent) => { const val = String(value); const target = e.target as HTMLInputElement; const index = +target.id.split('-')[2]; if (e.key == "Backspace") { let i = Math.max(0, val.length - 1) if (val.length >= maxLength && index < maxLength) { i = maxLength - 1; } inputRefs.current[i]?.current?.focus(); setPrevLength(() => i) } else { const i = Math.max(0, val.length) inputRefs.current[i]?.current?.focus(); setPrevLength(() => i) } } return (
{inputRefs?.current?.map((ref, i) => { return ( ) })}
) } export default OTPInputField