Formik has support for nested objects and arrays out of the box. These subjects are somewhat related because they both leverage the same syntax.
The name
props in Formik can use lodash-like dot paths to reference nested Formik values. This means that you do not need to flatten out your form's values anymore.
import React from 'react';import { Formik, Form, Field } from 'formik';export const NestedExample = () => (<div><h1>Social Profiles</h1><FormikinitialValues={{social: {facebook: '',twitter: '',},}}onSubmit={values => {// same shape as initial valuesconsole.log(values);}}><Form><Field name="social.facebook" /><Field name="social.twitter" /><button type="submit">Submit</button></Form></Formik></div>);
Formik also has support for arrays and arrays of objects out of the box. Using lodash-like bracket syntax for name
string you can quickly build fields for items in a list.
import React from 'react';import { Formik, Form, Field } from 'formik';export const BasicArrayExample = () => (<div><h1>Friends</h1><FormikinitialValues={{friends: ['jared', 'ian'],}}onSubmit={values => {// same shape as initial valuesconsole.log(values);}}><Form><Field name="friends[0]" /><Field name="friends[1]" /><button type="submit">Submit</button></Form></Formik></div>);
For more information around manipulating (add/remove/etc) items in lists, see the API reference section on the <FieldArray>
component.
If you want to avoid this default behavior Formik also has support for it to have fields with dots.
import React from 'react';import { Formik, Form, Field } from 'formik';export const NestedExample = () => (<div><h1>Social Profiles</h1><FormikinitialValues={{'owner.fullname': '',}}onSubmit={values => {// same shape as initial valuesconsole.log(values);}}><Form><Field name="['owner.fullname']" /><button type="submit">Submit</button></Form></Formik></div>);
The latest Formik news, articles, and resources, sent to your inbox.