Using React Hook Form with react-native - Part II (pre-filled values & conditional fields)
Tags: reactnative, javascript, react, tutorial
Published: 2020-10-03 12:56:59

This article is a continuation of [Part I](https://dev.to/sankhadeeproy007/using-react-hook-form-with-react-native-part-i-set-up-validation-31ca), where we added RHF to our react-native app. Please make sure you've read the first part for some context.

We'll now see how to pre-fill our fields with data fetched from a server. 

Let us make a request to get the `email` and `name` of a dummy user from [JSONPlaceholder](https://jsonplaceholder.typicode.com/). We add this block of code before the _return()_ statement inside our component (we might need to import _useEffect_ from `react` if it's not already imported). 

```react
useEffect(() => {
  fetchUser();
}, []);

const fetchUser = async () => {
  try {
    const response = await fetch(
      'https://jsonplaceholder.typicode.com/users/1'
    );
    const { name, email } = await response.json();
  } catch (error) {}
};
```

Now that we have the `email` and `name` values, we need to attach them to our form. To do so, we'll use the [setValue](https://react-hook-form.com/api#setValue) function from RHF.

```react
// add setValue to the list of destructured functions
const { handleSubmit, control, errors, setValue } = useForm();

// inside fetchUser function
const { name, email } = await response.json();
setValue('name', name);
setValue('email', email);

```
Now when we run our app, we'll notice that the name and email fields are filled with some values.

![Simulator Screen Shot - iPhone 11 - 2020-10-03 at 14.39.38](https://dev-to-uploads.s3.amazonaws.com/i/rflwobm5o180hefhrydd.png)

We can edit these values and when we click on submit, all the validation rules should work as expected.

Now, let us look at how we can add conditional fields to our form using RHF. In our current example, we are using _useState_ to control the toggling of the two extra fields.

![form](https://dev-to-uploads.s3.amazonaws.com/i/w6xrrdsl81v4dt7m2lqa.gif)

We'll now connect our switch to our form. To do so, we'll 
wrap our `<Switch />` component inside `Controller` from RHF.

```react
<Controller
    defaultValue={false}
    name="isBillingDifferent"
    control={control}
    render={({ onChange, value }) => (
      <Switch
        trackColor={{ false: color.gray200, true: color.green600 }}
        thumbColor={color.gray100}
        ios_backgroundColor={color.gray800}
        onValueChange={onChange}
        value={value}
      />
    )}
  />
```

Now we need to show/hide the additional fields based on the value of `isBillingDifferent`. To do so, we'll use the [watch](https://react-hook-form.com/api#watch) function from RHF. It watches the specified inputs and returns their value. 

```react
// add watch to the list of destructured functions from useForm
const { ...others,  watch } = useForm();

// watch isBillingDifferent as it changes
const isBillingDifferent = watch('isBillingDifferent');

```
Make sure we also delete the `isBillingDifferent` state that we had in our code. 

```react
// delete the following line
const [isBillingDifferent, setIsBillingDifferent] = useState(false);
```
There we have it! Now the additional fields will listen to the `isBillingDifferent` value to determine whether they need to render. 
The only thing that's left for us now is to wire up the additional fields to RHF. 

```react
<Controller
   defaultValue=""
   name="billingName"
   control={control}
   rules={{ required: { value: true, message: 'Billing name is required' } }}
   render={({ onChange, value }) => (
     <Input
       error={errors.billingName}
       errorText={errors?.billingName?.message}
       onChangeText={(text) => onChange(text)}
       value={value}
       placeholder="Billing Name"
     />
   )}
 />
<Controller
   defaultValue=""
   name="billingEmail"
   control={control}
   rules={{ required: { value: true, message: 'Billing email is required' }, pattern: { value: EMAIL_REGEX, message: 'Not a valid email' }
            }}
   render={({ onChange, value }) => (
     <Input
       error={errors.billingEmail}
       errorText={errors?.billingEmail?.message}
       onChangeText={(text) => onChange(text)}
       value={value}
       placeholder="Billing email"
     />
   )}
  />
```

Now we have a fully functional form with validation, pre-filled data and conditional fields!
This example is however only scratching the surface of what RHF can do. I have always struggled with forms and RHF is by far the simplest implementation I've seen so far! Let me know what your preferred solution is for forms in React.

Thanks for reading and do give it a ❤️ if you found it useful!
Happy coding!