Nested and array fields
A good form library should adapt to the shape of your data structure, not viceversa. And this is no exception.
#
Nested fieldsLet's take a form data structure with nested fields (and deeply nested fields):
We can reference these fields using the dot notation:
preferences.color
preferences.dish
preferences.place.street
preferences.place.city
preferences.place.state
Here is the complete example:
#
Array fieldsIn case you have arrays in your data structure:
You can also use the dot notation, with a number as key:
preferences.dishes.0
preferences.dishes.1
preferences.places.0.street
preferences.places.0.city
preferences.places.1.street
preferences.places.1.city
note
Other form libraries supports the dot notation with brackets. This is not supported:
preferences.dishes[0]
โ incorrect
preferences.dishes.0
โ
correct
<FieldArray/>
#
If you have arrays, probably you want the user to be able to add or remove items. To make your life easier, use the <FieldArray/>
component:
Few things to note:
<FieldArray/>
is very similar to<Field/>
, but it exposes useful properties to manage arrays.fields.names
is an array of field names; in the dishes example:["preferences.dishes.0", "preferences.dishes.1"]
.fields.push()
adds a new item to the array
#
useFieldArray<FieldArray />
is just a thin wrapper around its hook: useFieldArray
.
The same example can be written with useFieldArray
:
#
FieldScopeIn the previous example we wrote:
In this case we are concatenating the name of the array field ("preferences.places.0", "preferences.places.1", ...) with the name of the subfields ("street" and "city"). To avoid this, we can use the <FieldScope />
component:
<FieldScope />
is very useful when you have an entire component that manages a subset of your form, for example: