React Hook Form Tutorial - Prefilling Form Fields
/ 2 min read
There are some use cases of when we want a form to be prefilled:
- We want to modify an existing data.
- A form needs to be saved offline and get filled in later.
- Better user experience, like filling the default dates for hotel or flight bookings.
In this post we’re going to learn how to fill the form with some values the first time it is loaded.
We’re going to build a form that contains the following fields:
- Name: text field.
- Flight class: radio button.
- Terms of service agreement: checkbox.
Define the schema
We’ll skip the custom error messages for the sake of brevity.
Build the UI
We build the UI the same way we always do.
Setting default value
In order to set default values to our form, all we need to do is provide the value in the hook.
Now the prefilled data should show up the first time you open the page.
Wrapping Up
Here’s the sandbox code for you to try it yourself.