import { useState, useRef, useEffect } from 'react' import { XStack, Input } from 'tamagui' export const CodeInput = ({ onChange, codeLength }) => { const [inputValues, setInputValues] = useState(Array(codeLength).fill('')) const inputRefs = useRef<(Input | null)[]>([]) useEffect(() => { const newValue = inputValues.join('') onChange(newValue) }, [inputValues, onChange]) const handleChange = (val, index) => { if (/^\d*$/.test(val)) { const newInputValues = [...inputValues] newInputValues[index] = val setInputValues(newInputValues) if (val && index < codeLength - 1) { inputRefs.current[index + 1]?.focus() } } } const handleKeyPress = (e, index) => { if (e.nativeEvent.key === 'Backspace' && !inputValues[index] && index > 0) { inputRefs.current[index - 1]?.focus() } } return ( {inputValues.map((val, index) => ( { inputRefs.current[index] = el }} value={val} onChangeText={(text) => handleChange(text, index)} onKeyPress={(e) => handleKeyPress(e, index)} keyboardType="numeric" maxLength={1} textAlign="center" w="$5" h="$6" /> ))} ) }