Created
          September 4, 2022 06:54 
        
      - 
      
 - 
        
Save schriker/9ecd3d1130773f98f0d84e1413ea1003 to your computer and use it in GitHub Desktop.  
    Simple React Native One Time Password Input
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import React, { useRef } from 'react' | |
| import { NativeSyntheticEvent, TextInput, TextInputKeyPressEventData, View } from 'react-native' | |
| import { useStyles } from 'lib/hooks' | |
| import { createStyles } from 'lib/styles' | |
| import { Nullable } from 'lib/types' | |
| type OTPInputProps = { | |
| length: number, | |
| value: Array<string>, | |
| disabled: boolean, | |
| onChange(value: Array<string>): void | |
| } | |
| export const OTPInput: React.FunctionComponent<OTPInputProps> = ({ | |
| length, | |
| disabled, | |
| value, | |
| onChange | |
| }) => { | |
| const { styles } = useStyles(stylesheet) | |
| const inputRefs = useRef<Array<Nullable<TextInput>>>([]) | |
| const onChangeValue = (text: string, index: number) => { | |
| const newValue = value.map((item, valueIndex) => { | |
| if (valueIndex === index) { | |
| return text | |
| } | |
| return item | |
| }) | |
| onChange(newValue) | |
| } | |
| const handleChange = (text: string, index: number) => { | |
| onChangeValue(text, index) | |
| if (text.length !== 0) { | |
| return inputRefs?.current[index + 1]?.focus() | |
| } | |
| return inputRefs?.current[index - 1]?.focus() | |
| } | |
| const handleBackspace = (event: NativeSyntheticEvent<TextInputKeyPressEventData>, index: number) => { | |
| const { nativeEvent } = event | |
| if (nativeEvent.key === 'Backspace') { | |
| handleChange('', index) | |
| } | |
| } | |
| return ( | |
| <View style={styles.container}> | |
| {[...new Array(length)].map((item, index) => ( | |
| <TextInput | |
| ref={ref => { | |
| if (ref && !inputRefs.current.includes(ref)) { | |
| inputRefs.current = [...inputRefs.current, ref] | |
| } | |
| }} | |
| key={index} | |
| maxLength={1} | |
| contextMenuHidden | |
| selectTextOnFocus | |
| editable={!disabled} | |
| style={styles.input} | |
| keyboardType="decimal-pad" | |
| testID={`OTPInput-${index}`} | |
| onChangeText={text => handleChange(text, index)} | |
| onKeyPress={event => handleBackspace(event, index)} | |
| /> | |
| ))} | |
| </View> | |
| ) | |
| } | |
| const stylesheet = createStyles(template => ({ | |
| container: { | |
| width: '100%', | |
| flexDirection: 'row', | |
| justifyContent: 'space-between' | |
| }, | |
| input: { | |
| fontSize: 24, | |
| color: template.typography.regular, | |
| textAlign: 'center', | |
| width: 45, | |
| height: 55, | |
| backgroundColor: template.input.background, | |
| borderRadius: template.input.borderRadius, | |
| ...template.ui.createShadow() | |
| } | |
| })) | 
@devpolo Yes, I found it very tricky to handle autocompletion from SMS, I have another version of this component, which basically pastes the whole code to one input and then spread it over the other, it looks like this, but not very proud of it. There should be a better way to handle this.
import { NativeSyntheticEvent, TextInput, TextInputKeyPressEventData, View } from 'react-native'
import { useStyles } from 'lib/hooks'
import { createStyles } from 'lib/styles'
import { Nullable } from 'lib/types'
import { regexes } from 'lib/utils'
type OTPInputProps = {
    length: number,
    value: Array<string>,
    disabled: boolean,
    onChange(value: Array<string>): void
}
export const OTPInput: React.FunctionComponent<OTPInputProps> = ({
    length,
    disabled,
    value,
    onChange
}) => {
    const { styles } = useStyles(stylesheet)
    const [localState, setLocalState] = useState([...new Array(length)].map((item, index) => ({ index, value: '' })))
    const inputRefs = useRef<Array<Nullable<TextInput>>>([])
    const onChangeValue = (text: string, index: number) => {
        setLocalState(prevState => prevState.map(item => {
            if (item.index === index) {
                return {
                    index,
                    value: `${item.value}${text}`
                }
            }
            return {
                index: item.index,
                value: item.value
            }
        }))
        const newValue = value.map((item, valueIndex) => {
            if (valueIndex === index) {
                return text
            }
            return item
        })
        onChange(newValue)
    }
    const clearLocalState = () => {
        setLocalState([...new Array(length)].map((item, index) => ({ index, value: '' })))
    }
    const handleChange = (text: string, index: number) => {
        if (!regexes.isValidDigit(text)) {
            return
        }
        onChangeValue(text, index)
        if (text.length !== 0) {
            return inputRefs?.current[index + 1]?.focus()
        }
        return inputRefs?.current[index - 1]?.focus()
    }
    const handleKeyPress = (event: NativeSyntheticEvent<TextInputKeyPressEventData>, index: number) => {
        const { nativeEvent } = event
        if (nativeEvent.key === 'Backspace') {
            return handleChange('', index)
        }
        if (!regexes.isValidDigit(nativeEvent.key)) {
            return
        }
        if (value[index].length === 1) {
            return handleChange(nativeEvent.key, index)
        }
    }
    useEffect(() => {
        const longValue = localState.find(item => item.value.length === length)
        if (longValue) {
            onChange(longValue.value.split(''))
        }
    }, [localState])
    return (
        <View style={styles.container}>
            {[...new Array(length)].map((item, index) => (
                <TextInput
                    ref={ref => {
                        if (ref && !inputRefs.current.includes(ref)) {
                            inputRefs.current = [...inputRefs.current, ref]
                        }
                    }}
                    key={index}
                    maxLength={1}
                    value={value[index]}
                    contextMenuHidden
                    testID="OTPInput"
                    editable={!disabled}
                    style={styles.input}
                    onBlur={clearLocalState}
                    keyboardType="decimal-pad"
                    onChangeText={text => handleChange(text, index)}
                    onKeyPress={event => handleKeyPress(event, index)}
                />
            ))}
        </View>
    )
}
const stylesheet = createStyles(template => ({
    container: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    input: {
        width: 45,
        height: 55,
        fontSize: 24,
        fontWeight: '700',
        textAlign: 'center',
        color: template.input.OTPInputText,
        backgroundColor: template.input.background,
        borderRadius: template.input.borderRadius,
        ...template.ui.createShadow()
    }
}))
    If you cannot expose your library. How do you expect us to understand your code?
I mean, why don't you share the whole folder? or maybe relative files that are linked with this file for us to test it on our own?
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Very nice UI.
Unfortunately, the OTP input cannot be used with the autocomplete feature when receiving an SMS.