Default values
Setting default values in RVF is easy using the defaultValues
option in the useForm
hook.
const form = useForm({
// ...validator and other options
defaultValues: {
firstName: "Jane",
lastName: "Doe",
email: "jane.doe@example.com",
},
});
Type safety
For modern forms using a Standard Schema validator, it's required to set default values.
The type of defaultValues
is inferred from your schema.
The types of the form
object returned by useForm
(form.value()
, form.setValue()
, etc)
are based around the inferred input type.
If you're using a legacy validator
, the type of defaultValues
is not inferred from your validator, ando only from defaultValues
.
const form = useForm({
schema: z.object({
name: z.string(),
}),
// Type inferred from schema above!
defaultValues: {
selectedOption: "",
},
});
In some cases, a value that can occur while filling out the form, won't be present in the schema.
In this case you can widen the type by casting a field inside defaultValues
.
const form = useForm({
schema: z.object({
selectedOption: z.string(),
}),
defaultValues: {
// Widens the type of `selectedOption` to `string | null`
selectedOption: null as string | null,
},
});