From 245137b946b2def9156698d3e435aee7f44f5c6e Mon Sep 17 00:00:00 2001 From: Aliaksandr Kazerski Date: Thu, 7 Dec 2023 15:11:54 +0300 Subject: [PATCH] fix: autocomplete issue for mobile devices. --- src/index.tsx | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 8b92566..80e9a0a 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -2,7 +2,8 @@ import React, { useRef, useEffect, useImperativeHandle, - forwardRef + forwardRef, + ChangeEvent } from 'react'; const allowedCharactersValues = ['alpha', 'numeric', 'alphanumeric'] as const; @@ -183,6 +184,31 @@ const AuthCode = forwardRef( e.preventDefault(); }; + const handleOnInput = (event: ChangeEvent) => { + if (!event.target.value) return; + const { + target: { value }, + } = event; + let currentInput = 0; + + if (event.target.value && event.target.value.length === length) { + for (let i = 0; i < value.length; i++) { + const pastedCharacter = value.charAt(i); + if (pastedCharacter.match(inputProps.pattern)) { + inputsRef.current[currentInput].value = pastedCharacter; + if (inputsRef.current[currentInput].nextElementSibling !== null) { + ( + inputsRef.current[currentInput] + .nextElementSibling as HTMLInputElement + ).focus(); + currentInput++; + } + } + } + sendResult(); + } + }; + const inputs = []; for (let i = 0; i < length; i++) { inputs.push( @@ -192,12 +218,12 @@ const AuthCode = forwardRef( onKeyDown={handleOnKeyDown} onFocus={handleOnFocus} onPaste={handleOnPaste} + onInput={handleOnInput} {...inputProps} type={isPassword ? 'password' : inputProps.type} ref={(el: HTMLInputElement) => { inputsRef.current[i] = el; }} - maxLength={1} className={inputClassName} autoComplete={i === 0 ? 'one-time-code' : 'off'} aria-label={