question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to handle array of fields

See original GitHub issue

Hi, so say my user API had a nested array like this:

{
   id: string,
   email: string,
   pets: [
     { type: string, name: string }
   ]
}

Is there a way to implement this kind of form, where i’ll be able to add 0-many pets?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:16 (4 by maintainers)

github_iconTop GitHub Comments

14reactions
jaredpalmercommented, Jul 1, 2017

Yes, you can create a mapPropsToValues function that would flatten the array and prefix/suffix each item.

const withFormik = Formik(
  ...
  mapPropsToValues: ({id, email, pets}) => ({
      id,
      email,
      ...(pets.reduce((accum, current, index) => Object.assign(accum, {
        [`pet_type_{index}`]: current.type,
        [`pet_name_{index}`]: current.name,
      }), {})
    })
  ...
)

This results in props.values that’s equivalent to:

{
   id: string,
   email: string,
   pet_type_1: string,
   pet_name_1: string,
   pet_type_2: string,
   pet_name_2: string,
   ...
   pet_type_n: string,
   pet_name_n: string,
}

There are many ways to then display the pets. Using Object.keys and filter what I usually use in this situation. However, it really depends on your requirements. In the case of arbitrarily adding pets, you’ll need to use props.setValues which allows you to declaratively call setState on just the key of Formik.state.values. This will modify props.values. If you need to rearrange or delete pets arbitrarily, you would not use the pets array index, but rather a uuid to uniquely identify each pet in the flattened state tree. Anyways, here’s the simplest case (when the number of pets doesn’t change).

// example of a form with a nested array that doesn't change size
const myForm = ({  values, handleSubmit, handleChange }) => (
  <form onSubmit={handleSubmit}>
    <input type="email" onChange={handleChange} id="email" />
    {Object.key(values).filter(v => v.startsWith('pet')).map((pet, i) => {
      <span>
        <input type="text" id={`pet_type_${i}`} value={values[`pet_type_${i}`]} onChange={handleChange} />
        <input type="text" id={`pet_name_${i}`} value={values[`pet_name_${i}`]} onChange={handleChange} />
      </span>
    })}
    <button type="submit">Submit</button>
  </form>
)

Hope that helps.

13reactions
ronyfhebriancommented, Oct 9, 2020

What about arrays with useFormik? I have already used useFormik and now kinda confused of how to make arrays of components from initialValues, the values are updating but the component doesn’t. Please help

Read more comments on GitHub >

github_iconTop Results From Across the Web

useFieldArray - Simple React forms validation
Each useFieldArray is unique and has its own state update, which means you should not have multiple useFieldArray with the same name ....
Read more >
Field Arrays Example - Redux Form
This example demonstrates how to have arrays of fields, both an array of one field or of a group of fields. In this...
Read more >
How to get values from html input array using JavaScript
To access all the values entered in input fields use the following method: var input = document. getElementsByName('array[]'); The document.
Read more >
get array data into input fields - javascript - Stack Overflow
You can try like this. You can add any input field with the array of object data. I have separated each array item...
Read more >
Making dynamic form inputs with React - Gosha Arinich
Among other fields, a company has a variable number of shareholders. Typically when dealing with array inputs, here are the things we can...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found