Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
2
Indexable
import React, { useRef } from 'react';
import { View, StyleSheet } from 'react-native';

import PhoneInput from 'react-native-phone-input';
import { colors, fontSizes, spacings } from '../../../theme';
import { Controller } from 'react-hook-form';
import { HelperText } from 'react-native-paper';
import { useTranslation } from 'react-i18next';

export const CustomPhoneNumberInput = ({
    control,
    name,
    defaultValue,
}: {
    control: any;
    name: string;
    defaultValue?: string;
}) => {
    const { t } = useTranslation();
    const phoneRef = useRef<PhoneInput>(null);

    return (
        <Controller
            control={control}
            name={name}
            rules={{ validate: (phoneRef) => phoneRef.current?.isValidNumber === true }}
            render={({ field: { onChange }, fieldState: { error } }) => (
                <View>
                    <PhoneInput
                        style={styles.phoneInput}
                        ref={phoneRef}
                        initialCountry="no"
                        onChangePhoneNumber={onChange}
                        initialValue={defaultValue}
                        textStyle={styles.phoneInputTextStyles}
                        cancelText={t('cancel')}
                        confirmText={t('confirm')}
                        autoFormat
                        textProps={{ autoFocus: true }}
                    />
                    {error && (
                        <HelperText style={styles.helperTextStyle} type="error">
                            {t('custom.phoneNumber.input.invalid_phoneNumber')}
                        </HelperText>
                    )}
                </View>
            )}
        />
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        paddingRight: spacings.medium,
        paddingLeft: spacings.medium,
    },
    phoneInput: {
        borderBottomColor: colors.gray7,
        borderBottomWidth: 1,
        borderRadius: spacings.xsmall2,
        padding: spacings.medium,
        marginRight: spacings.medium,
        marginLeft: spacings.medium,
    },
    phoneInputTextStyles: {
        fontSize: fontSizes.xlarge2,
    },
    helperTextStyle: {
        paddingLeft: spacings.medium,
        color: colors.error,
    },
});