$ git show otp-input
Code input
One-time-code boxes where each digit pops in as you type, the next box glows, and a wrong code shakes the row.
4815
// Reanimated 4: CSS animations for the caret and the shake, transitions for the active border
import Animated, { ZoomIn } from 'react-native-reanimated';
const LEN = 4;
const blink = { '0%': { opacity: 1 }, '50%': { opacity: 0 }, '100%': { opacity: 1 } };
const shakeKeyframes = {
'0%': { transform: [{ translateX: 0 }] }, '20%': { transform: [{ translateX: -10 }] },
'40%': { transform: [{ translateX: 10 }] }, '60%': { transform: [{ translateX: -6 }] },
'100%': { transform: [{ translateX: 0 }] },
};
const [code, setCode] = useState('');
const [fails, setFails] = useState(0); // bump to replay the shake
const input = useRef(null);
const onChange = async (text) => {
const digits = text.replace(/\D/g, '').slice(0, LEN);
setCode(digits);
if (digits.length === LEN && !(await verify(digits))) { setFails((n) => n + 1); setCode(''); }
};
<Pressable onPress={() => input.current?.focus()}>
<Animated.View
key={fails}
style={{ flexDirection: 'row', gap: 8, animationName: fails ? shakeKeyframes : undefined, animationDuration: '250ms' }}>
{Array.from({ length: LEN }, (_, i) => (
<Animated.View key={i} style={[styles.box, {
borderColor: i === code.length ? '#2F54EB' : '#DADFE6',
transitionProperty: 'borderColor',
transitionDuration: '150ms',
}]}>
{code[i]
? <Animated.Text entering={ZoomIn.springify().damping(12)} style={styles.digit}>{code[i]}</Animated.Text>
: i === code.length && (
<Animated.View style={[styles.caret, {
animationName: blink, animationDuration: '1s', animationIterationCount: 'infinite',
}]} />
)}
</Animated.View>
))}
</Animated.View>
<TextInput ref={input} value={code} onChangeText={onChange} keyboardType="number-pad"
textContentType="oneTimeCode" autoComplete="sms-otp" maxLength={LEN} style={styles.hidden} />
</Pressable>