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 fields#
Let's take a form data structure with nested fields (and deeply nested fields):
We can reference these fields using the dot notation:
preferences.colorpreferences.dishpreferences.place.streetpreferences.place.citypreferences.place.state
Here is the complete example:
Array fields#
In case you have arrays in your data structure:
You can also use the dot notation, with a number as key:
preferences.dishes.0preferences.dishes.1preferences.places.0.streetpreferences.places.0.citypreferences.places.1.streetpreferences.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.namesis 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:
FieldScope#
In 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: