UNPKG

rn-otp-input-field

Version:

rn-otp-input-field A customizable OtpScreen screen component for React Native projects. Use this open source library in your fresh React Native project for instant startup.

72 lines (61 loc) 1.76 kB
import React, { useState, useRef } from "react"; import { View, TextInput, StyleSheet } from "react-native"; const OtpScreen = ({ length, containerStyle, otpInputStyle }) => { const [otp, setOtp] = useState(""); const otpInputRefs = useRef([]); const handleOtpChange = (value, index) => { const newOtp = otp.split(""); newOtp[index] = value; setOtp(newOtp.join("")); if (index < length - 1 && value !== "") { otpInputRefs.current[index + 1].focus(); } }; const handleOtpKeyPress = (event, index) => { if (event.nativeEvent.key === "Backspace" && index > 0) { otpInputRefs.current[index - 1].focus(); } }; const renderOtpInputs = () => { const otpInputs = []; for (let i = 0; i < length; i++) { otpInputs.push( <TextInput key={i} ref={(ref) => (otpInputRefs.current[i] = ref)} style={[styles.otpInput, otpInputStyle]} value={otp[i] || ""} onChangeText={(value) => handleOtpChange(value, i)} onKeyPress={(event) => handleOtpKeyPress(event, i)} maxLength={length} keyboardType="numeric" textContentType="oneTimeCode" autoFocus={i === 0} /> ); } return otpInputs; }; return ( <View style={[styles.container, containerStyle]}>{renderOtpInputs()}</View> ); }; const styles = StyleSheet.create({ container: { flexDirection: "row", justifyContent: "space-around", alignItems: "center", marginVertical: 20, }, otpInput: { width: 40, height: 40, borderRadius: 5, borderWidth: 1, borderColor: "#ccc", fontSize: 18, textAlign: "center", backgroundColor: "lightgrey", }, }); export default OtpScreen;