Untitled

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

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

export const CustomPhoneNumberInput = ({
    control,
    name,
    defaultValue,
    rules,
}: {
    control: any;
    name: string;
    defaultValue?: string;
    rules?: object;
}) => {
    const phoneRef = useRef<PhoneInput>(null);
    console.log('phoneRef', phoneRef.current?.isValidNumber());

    return (
        <Controller
            control={control}
            name={name}
            rules={phoneRef.current?.isValidNumber() === false ? { required: true } : rules}
            render={({ field: { onChange }, fieldState: { error } }) => (
                <View>
                    <PhoneInput
                        style={styles.phoneInput}
                        ref={phoneRef}
                        initialCountry="no"
                        onChangePhoneNumber={onChange}
                        initialValue={defaultValue}
                        autoFormat
                    />
                    {error && (
                        <HelperText style={styles.helperTextStyle} type="error">
                            {error.message || error}
                        </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,
    },
    helperTextStyle: {
        paddingLeft: spacings.medium,
        color: colors.error,
    },
});