Skip to content

Instantly share code, notes, and snippets.

@olalekanteeblaze
Created September 10, 2024 19:52
Show Gist options
  • Save olalekanteeblaze/d1b7f9228fbd711aab94f40800e92d73 to your computer and use it in GitHub Desktop.
Save olalekanteeblaze/d1b7f9228fbd711aab94f40800e92d73 to your computer and use it in GitHub Desktop.
import React, { useState, useRef } from 'react';
import { View, TextInput, StyleSheet, Dimensions } from 'react-native';
const { width } = Dimensions.get('window');
const INPUT_WIDTH = (width - 120) / 4; // Subtracting 100 for padding and gaps
interface OTPInputProps {
getOtp: (otp: string) => void;
index: number | null;
}
const OTPInput: React.FC<OTPInputProps> = ({ getOtp, index }) => {
const [otp, setOtp] = useState(['', '', '', '']);
const inputRefs = useRef<Array<TextInput | null>>([]);
const handleOtpChange = (value: string, index: number) => {
// Allow only numeric input
if (!/^\d*$/.test(value)) return;
const newOtp = [...otp];
newOtp[index] = value;
setOtp(newOtp);
getOtp(newOtp.join(''));
if (value && index < 3) {
inputRefs.current[index + 1]?.focus();
} else if (!value && index > 0) {
inputRefs.current[index - 1]?.focus();
}
};
return (
<View style={styles.container}>
{otp.map((digit, idx) => (
<TextInput
key={idx}
ref={(ref) => (inputRefs.current[idx] = ref)}
style={[
styles.input,
idx === index ? styles.focusedInput : null,
{ borderColor: idx === index ? '#EE1C23' : '#D1D3D8' }
]}
maxLength={1}
keyboardType="numeric"
onChangeText={(value) => handleOtpChange(value, idx)}
value={digit}
autoFocus={idx === 0}
/>
))}
</View>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
// justifyContent: 'center',
// alignItems: 'center',
marginVertical: 20,
},
input: {
width: INPUT_WIDTH,
height: INPUT_WIDTH,
borderWidth: 1,
borderRadius: 12,
textAlign: 'center',
fontSize: 24,
fontWeight: 'bold',
marginHorizontal: 5,
},
focusedInput: {
borderWidth: 2,
},
});
export default OTPInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment