Formik: Rendering form with array of objects

Created on 4 Sep 2017  路  6Comments  路  Source: formium/formik

I have the following problem:

I'm trying to render multiple input fields based on index such as:

{values.education.map((item, index) => getInputFields(index))}

where values contains an array of objects as:

education: [ 
{
what: '',
where: '',
description: '',
startDate: '',
endDate: ''
} 
]

and getInputFields(index) renders a set of input fields based on the education index.

The problem im running into is that if i use the default handleChange from formik, the values object i get is:

{
education[0].what: ''
education[0].where: '',
education[0].description: '',
education[0].startDate: '',
education[0].endDate: ''
}

So i decided to implement a custom onChange handler that uses the setFieldValue to manually set education. It works up to a point. Now my errors and touched objects are not working. Errors return the exact same object as before:

{
education[0].what: 'This field is required.'
education[0].where: 'This field is required.',
education[0].description: 'This field is required.',
education[0].startDate: '',
education[0].endDate: ''
}

Is there a special way to handle a form with an array of objects?

Will this feature be implemented anytime soon in formik?

Duplicate Question

Most helpful comment

Something similar to this would be great https://redux-form.com/7.0.4/docs/api/fieldarray.md/

All 6 comments

Quick solution is to pick unique input names. In this particular situation, I would pick names such as education.{index}.what, education.{index}.where, and so on.

When processing values I would convert from flat list into nested structure.

my input names do use unique names education[{index}].what etc.. it would be a not-so-elegant solution to convert a flat list into a nested structure... but if thats the only way..

if formik would use path instead of field name, itd be so helpful.

Something similar to this would be great https://redux-form.com/7.0.4/docs/api/fieldarray.md/

My input names do use unique name address.label, address.coordinates, I don't event use Array yet, but it would be so awesome to support path to avoid transforming for each form nested Object to Flat List and the other way around from values

I actually created pull request to remedy this #202 . Do you think it will cover all cases? For both arrays and nested values?

Merged with #207

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jordantrainor picture jordantrainor  路  3Comments

najisawas picture najisawas  路  3Comments

green-pickle picture green-pickle  路  3Comments

giulioambrogi picture giulioambrogi  路  3Comments

outaTiME picture outaTiME  路  3Comments