Working with Form Values of Different Structures
Learn how to work with form values of different structures.
When we specify the initialValues
for our form, we make use of key-value pairs where each key represents a field in the form and the value represents the value of the corresponding field.
This satisfies most of our form’s needs, but sometimes, the API endpoint we intend to send our form’s data to requires that values
is structured in a different way. Other times, the logic of our form will prefer a more dynamic structure of our form values.
Formik gives us a lot of flexibility with the way we structure the initialValues
of our form. We’ll see two ways through which we can attain this much-needed flexibility.
Nested objects
Sometimes, we want to group some form fields in the same object, so that it’s easier for us to send it to the API or database without having to restructure the values. Beyond the needs of our APIs or databases, we may also want to give some nice structure to our form values by grouping related fields together. For example, instead of the following:
const initialValues = {firstName: "",lastName: "",otherName: "",age: "",phone: "",email: "",}
We do this:
const initialValues = {name: {firstName: "",lastName: "",otherName: "",},age: "",contact: {phone: "",email: "",}}
In the second ...
Get hands-on with 1400+ tech skills courses.