0

In react native I want to make a dynamic controller component. But i cant access errors with it. I using "react-hook-form" for form elements. So Its my component :

 const {
    control,
    handleSubmit,
    formState: {errors},
    setValue,
  } = useForm();
    const DynamicController = ({req, pattern, name, label}) => {
        return (
          <>
            <Text style={[t.textBase]}>{label}</Text>
            <Controller
              control={control}
              defaultValue=""
              rules={{
                required: {
                  value: true,
                  message: 'Bu alan boş bırakılamaz!',
                },
              }}
              render={({field: {onChange, onBlur, value}}) => (
                <Input
                  errorText={errors[name].message}
                  error={errors[name]}
                  onBlur={onBlur}
                  placeholder={label}
                  onChangeText={onChange}
                  value={value}
                />
              )}
              name={name}
            />
          </>
        );
      };

My Input Component is basicly simple input. My problem is when i give error name like that example i cant access errors.

Its how i use my component :

<DynamicController
              label="Email"
              name="Email"
              pattern={true}
              req={true}
            />

When i dont fill the element and log the submit its not showing any error. Its simple passing validate. So what can i do where do i make wrong ? thank you for answerings!!!

1 Answer 1

0

Is your Input a custom wrapper? If not, a better way do this using react-hook-form would be:

const {
    control,
    handleSubmit,
    formState: {errors},
    setValue,
  } = useForm(
  defaultValues: {
      firstName: '', // form fields should be populated here so that the error can be displayed appropriately 
      lastName: ''
    }
);
    const DynamicController = ({req, pattern, name, label}) => {
        return (
          <>
            <Text style={[t.textBase]}>{label}</Text>
            <Controller
              control={control}
              defaultValue=""
              rules={{
                required: {
                  value: true,
                  message: 'Bu alan boş bırakılamaz!',
                },
              }}
              render={({field: {onChange, onBlur, value}}) => (
                <Input
                  onBlur={onBlur}
                  placeholder={label}
                  onChangeText={onChange}
                  value={value}
                />
              )}
              name={name}
            />
             {errors[name] && <Text>This is required.</Text>}
          </>
        );
      };
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.