Created
March 30, 2020 16:42
-
-
Save tandu/0788addcf6624a5a84b50adb0bd7e728 to your computer and use it in GitHub Desktop.
This file contains 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, { useState, useRef } from 'react'; | |
import { Text, TextInput, View, NativeSyntheticEvent, TextInputKeyPressEventData, TextInputSelectionChangeEventData } from 'react-native'; | |
import COLORS from '../styles/Colors'; | |
import Styles from '../styles/Styles'; | |
import PhoneNumberUtils from '../utils/PhoneNumberUtils'; | |
const PhoneNumberEntryComponent = | |
({ | |
phoneNumber, | |
setPhoneNumber, | |
countryCode, | |
setCountryCode, | |
allowKeyboardInput, | |
autoFocus }) => { | |
const US_PHONE_NUMBER_PLACEHOLDER = '(___) ___-____'; | |
const [phoneNumberPlaceholder, setPhoneNumberPlaceholder] = useState(US_PHONE_NUMBER_PLACEHOLDER); | |
const inputRef = useRef<TextInput>(); | |
const handleBackspace = (e: NativeSyntheticEvent<TextInputKeyPressEventData>) => { | |
e.preventDefault(); | |
console.log('selection', (inputRef.current as any).selection); | |
const updatedPhoneNumber = PhoneNumberUtils | |
.getRawPhoneNumber(phoneNumber) | |
.slice(0, -1); | |
setPhoneNumber(PhoneNumberUtils.phoneFormat(countryCode, updatedPhoneNumber)); | |
} | |
return ( | |
<View > | |
<Text allowFontScaling={false} style={[Styles.center, Styles.cashierInstructionsH1]}>Enter Phone Number</Text> | |
<View style={Styles.centeredInputContainer}> | |
<Text allowFontScaling={false} style={Styles.countryCodePlus}>+</Text> | |
<TextInput | |
allowFontScaling={false} | |
style={[Styles.largeTextInput, Styles.centeredInputContainerMinWidth, { minWidth: 40 }]} | |
autoCapitalize="none" | |
autoCorrect={false} | |
placeholderTextColor={COLORS.GRAY} | |
placeholder={''} | |
value={countryCode} | |
editable={allowKeyboardInput} | |
keyboardType={"number-pad"} | |
onChangeText={value => { | |
setPhoneNumberPlaceholder(value === '1' ? US_PHONE_NUMBER_PLACEHOLDER : ''); | |
setCountryCode(value); | |
}} | |
maxLength={6} | |
/> | |
<TextInput | |
allowFontScaling={false} | |
style={[Styles.largeTextInput, Styles.centeredInputContainerMinWidth]} | |
autoCapitalize="none" | |
autoCorrect={false} | |
placeholderTextColor={COLORS.GRAY} | |
placeholder={phoneNumberPlaceholder} | |
value={phoneNumber} | |
editable={allowKeyboardInput} | |
keyboardType={"number-pad"} | |
ref={inputRef} | |
onKeyPress={e => { | |
if (e.nativeEvent.key === 'Backspace') handleBackspace(e); | |
}} | |
onChangeText={ value => setPhoneNumber(PhoneNumberUtils.phoneFormat(countryCode, value)) } | |
autoFocus={autoFocus} | |
/> | |
</View> | |
</View> | |
); | |
}; | |
export default PhoneNumberEntryComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment