Hello i'm fairly new to react native development for a few weeks and i'm attempting to connect react hook forms with a custom picker i implemented. The custom picker consists of a disabled text input that when click pops up a modal and the user can select a country code. But how can we validate an option is selected with react hook forms.I tried updating the state with setValue
but this doesn't get triggered.
Code:
interface ExtrafieldProp {}export type CountryCodeDropDownProp = ExtrafieldProp & TextInputPropsexport default function CountryCodeDropDown(props: CountryCodeDropDownProp) { const [selectedValue, setSelectedValue] = useState('') const [hidePicker, setHidePicker] = useState(false) const hideCountrycodePicker = () => setHidePicker(false) const onBlur = () => setHidePicker(false) const getCountryCode = (value: string) => { setSelectedValue(`+${value}`) setHidePicker(false) } return (<><Container width={props.width} onPress={() => setHidePicker(!hidePicker)}><Wrapper pointerEvents='none'><Input editable={false} placeholder={'state'} value={selectedValue} keyboardType='default' autoCorrect={false} autoCapitalize='none' onFocus={hideCountrycodePicker} onBlur={onBlur} onChangeText={getCountryCode} /></Wrapper></Container><CountryCodePicker isVisible={hidePicker} hidePicker={hideCountrycodePicker} getCountryCode={getCountryCode} /></> )}interface ContainerProp { width?: number}const Container = styled.Pressable<ContainerProp>` width: ${(props) => `${props.width}px` || '100%'};`const Wrapper = styled.View``
Wrap CountryCodeDropDown with react hook form
export type RhfSelectFieldProps<T extends FieldValues> = CountryCodeDropDownProps & UseControllerProps<T> & UseFormProps<T>export const RhfSelectField = <T extends FieldValues>(props: RhfSelectFieldProps<T>) => { return (<Controller control={props.control} name={props.name} rules={props.rules} render={(fieldProps) => { return (<><CountryCodeDropDown {...props} value={fieldProps.field.value} onChangeText={(value: string) => { // fails to update value props.setValue(props.name, value) }} onBlur={fieldProps.field.onBlur} /> {fieldProps.formState.errors[props.name] && (<ErrorText fontSize={sizes.xsmall} style={{ alignSelf: 'center' }}> { ( fieldProps.formState.errors[props.name] as DeepMap< FieldValues, FieldError> )?.message }</ErrorText> )}</> ) }} /> )}
In my main screen:
code: yup.string().required('This field is required'),const { control, handleSubmit, formState: { errors }, setValue,} = useForm<CountryCodeValue>({ resolver: yupResolver(countryCodeSchema), defaultValues: { code: '', }, mode: 'onChange',})<RhfSelectField width={width * 0.23} name={'code'} control={control} />
I am able to load the modal picker and select a country code but when i attempt to submit react-hook-form complains the field is required meaning it never registered the value. Please any assistance or guidance would be appreciated.