@@ -29,33 +29,53 @@ export function Otp({ length, style, onChangeText, autoFocus }: OtpProps) {
29
29
30
30
if ( text . length <= 1 ) {
31
31
newValue = [ ...value . slice ( 0 , index ) , text , ...value . slice ( index + 1 ) ] ;
32
+ } else if ( text . length === length ) {
33
+ // Paste OTP
34
+ newValue = text . split ( '' ) ;
35
+ focusInputField ( 'next' , length - 1 ) ;
36
+ } else if ( text . length === 2 ) {
37
+ // Replace value
38
+ newValue = [
39
+ ...value . slice ( 0 , index ) ,
40
+ ( value [ index ] === text [ 0 ] ? text [ 1 ] : text [ 0 ] ) ?? '' ,
41
+ ...value . slice ( index + 1 )
42
+ ] ;
32
43
} else {
33
- newValue = text . split ( '' , length ) ;
44
+ newValue = [ ...value . slice ( 0 , index ) , text [ 0 ] || '' , ...value . slice ( index + 1 ) ] ;
45
+ focusInputField ( 'next' , index ) ;
34
46
}
35
47
36
48
setValue ( newValue ) ;
37
49
onChangeText ?.( newValue . join ( '' ) ) ;
50
+ } ;
51
+
52
+ const focusInputField = ( dir : 'prev' | 'next' , currentIndex : number , clear = false ) => {
53
+ let newIndex ;
54
+ if ( dir === 'prev' && currentIndex > 0 ) {
55
+ newIndex = currentIndex - 1 ;
56
+ } else if ( dir === 'next' && currentIndex < length - 1 ) {
57
+ newIndex = currentIndex + 1 ;
58
+ }
38
59
39
- if ( text . length === 1 && index < length - 1 ) {
40
- refArray [ index + 1 ] ?. current ?. focus ( ) ;
41
- } else if ( text . length > 1 ) {
42
- refArray [ newValue . length ] ?. current ?. focus ( ) ;
60
+ if ( newIndex !== undefined ) {
61
+ refArray [ newIndex ] ?. current ?. focus ( ) ;
62
+ if ( clear ) {
63
+ refArray [ newIndex ] ?. current ?. clear ( ) ;
64
+ _onChangeText ( '' , newIndex ) ;
65
+ }
43
66
}
44
67
} ;
45
68
46
69
const onKeyPress = ( e : NativeSyntheticEvent < TextInputKeyPressEventData > , index : number ) => {
47
70
const currentValue = value [ index ] || '' ;
71
+ const key = e . nativeEvent . key ;
48
72
49
- if ( e . nativeEvent . key !== 'Backspace' && currentValue && index !== length - 1 ) {
50
- refArray [ index + 1 ] ?. current ?. focus ( ) ;
51
-
52
- return ;
53
- }
54
-
55
- if ( e . nativeEvent . key === 'Backspace' && index !== 0 ) {
73
+ if ( key === 'Backspace' ) {
56
74
if ( ! currentValue ) {
57
- refArray [ index - 1 ] ?. current ?. focus ( ) ;
75
+ focusInputField ( 'prev' , index , true ) ;
58
76
}
77
+ } else {
78
+ focusInputField ( 'next' , index ) ;
59
79
}
60
80
} ;
61
81
@@ -70,7 +90,6 @@ export function Otp({ length, style, onChangeText, autoFocus }: OtpProps) {
70
90
inputRef = { refArray [ index ] }
71
91
onChangeText = { text => _onChangeText ( text , index ) }
72
92
onKeyPress = { ( e : any ) => onKeyPress ( e , index ) }
73
- selectTextOnFocus
74
93
textContentType = "oneTimeCode"
75
94
autoComplete = { Platform . OS === 'android' ? 'sms-otp' : 'one-time-code' }
76
95
/>
0 commit comments