I'm using material-ui in my react project. I wanna copy a number and paste in multiple text fields.
const [otpArr, setOtpArr] = useState<string[]>(['', '', '', '', '', ''])
let inputRefs = useRef([React.createRef<HTMLDivElement>(), React.createRef<HTMLDivElement>(), React.createRef<HTMLDivElement>(), React.createRef<HTMLDivElement>(), React.createRef<HTMLDivElement>(), React.createRef<HTMLDivElement>()])
{otpArr && otpArr.map((x, index) => (
<NumberTextField
inputRef={inputRefs.current[index]}
variant='outlined'
size='small'
id='otp'
value={x}
key={index}
onChange={(e: any) => {
const temp = [...otpArr]
temp[index] = e.target.value
setOtpArr(temp)
if ((index < otpArr.length - 1) && e.target.value.length === 1) {
inputRefs.current[index 1]?.current?.focus()
}
}}
inputProps={{ maxLength: 1 }}
style={{
width: '3rem',
direction: 'ltr',
marginTop: '3rem',
}}
/>
))}
any solution?
CodePudding user response:
Here is a working example: https://codesandbox.io/s/simple-6-digite-input-past-2qqdg
You can read the paste
event and get the 6 digit with an event listener:
// listen "paste" event in useEffect
useEffect(() => {
const onPaste = (e) => {
let paste = (e.clipboardData || window.clipboardData).getData("text");
paste = paste.toUpperCase().split("");
if (paste.length === 6) {
setValue(paste);
}
};
document.addEventListener("paste", onPaste);
return () => {
document.removeEventListener("paste", onPaste);
};
}, [value]);
PS: You can add Event on an input element