Last active
January 12, 2024 19:04
-
-
Save valakhosravi/504c1b18a0e7a560379167fdd2327f73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useRef } from "react"; | |
export default function InputCode({ length }: { length: number }) { | |
const inputRefs = Array.from({ length }, () => | |
useRef<HTMLInputElement>(null) | |
); | |
useEffect(() => { | |
const handleKeyPress = (index: number, event: KeyboardEvent) => { | |
setTimeout(() => { | |
if (event.key === "Backspace" && index > 0) { | |
inputRefs[index - 1].current?.focus(); | |
} else if ( | |
event.key !== "Backspace" && | |
event.key.length === 1 && | |
index < inputRefs.length - 1 | |
) { | |
inputRefs[index + 1].current?.focus(); | |
} | |
}, 10); | |
}; | |
inputRefs.forEach((ref, index) => { | |
ref.current?.addEventListener("keydown", (event) => | |
handleKeyPress(index, event) | |
); | |
}); | |
return () => { | |
inputRefs.forEach((ref, index) => { | |
ref.current?.removeEventListener("keydown", (event) => | |
handleKeyPress(index, event) | |
); | |
}); | |
}; | |
}, [inputRefs]); | |
return ( | |
<div className="flex w-full -mx-[4px]"> | |
{inputRefs.map((inputRef, index) => ( | |
<div className="w-full mx-[4px]" key={index}> | |
<input | |
onPaste={($event) => { | |
const clipboardData = $event.clipboardData; | |
const pastedText = clipboardData.getData("text"); | |
pastedText | |
.slice(0, length) | |
.split("") | |
.forEach((char, index) => { | |
if (inputRefs[index].current) { | |
(inputRefs[index].current as any).value = char; | |
} | |
}); | |
$event.preventDefault(); | |
}} | |
className="text-center rounded-[12px] w-[inherit] p-[12px] border border-black-400 h-[64px]" | |
key={index} | |
ref={inputRef} | |
type="text" | |
maxLength={1} | |
style={{ marginRight: "10px" }} | |
onFocus={($event) => { | |
$event.target.select(); | |
}} | |
/> | |
</div> | |
))} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment