Skip to content
Advertisement

How to set Formik FieldArray select options at various index values based on another selection

I am using a Formik FieldArray that consists of the following fields:

JavaScript

My initialValues setup for this FieldArray is as follows:

JavaScript

Based on the selection value for Pet Type, I need to assign a specific set of options to Pet Food. Obviously I need to make sure that values are maintained at each row index level.

Assuming I have the following options for Pet Type

JavaScript

The following are the two types of food options bases on pet selection:

JavaScript

Assuming my FieldArray index is at 0:

JavaScript

Based on Pet Type selection of dog how can I then set the following select to have the options of dogFood at index 0, that is:

JavaScript

Now if the user adds another row within the FieldArray, now at index 1 and now select cat, how can I set the options to now use catFood at index 1 ?

JavaScript

I am not sure how to set these Pet Food options at various indexes based on Pet List selection within my FieldArray.

Advertisement

Answer

So, to understand correctly, you have to render a list of controls, one that makes selection of which type of pet and then based off of the first selection, the program renders the food options to choose from.

JavaScript

The value selected from the first list would determine what options to render next. Therefore as an ease for retrival I have kept the key of the petFood array below to match the set set of possible values returned from first selection above.

JavaScript

To save the values of petType and petFood we pass an array with the first object initialized where both petType and food properties are set to empty. This will render out just one set of row(s).

In the code below : <Field name={petSelection.${index}.petType} as="select" value={selectedPet.petType}> ... </Field> tells formik of how to store the value of the selection. Notice the name property on FieldArray. The property where you would want to store the value should then be FieldArray's name <dot> Index. If we want to place our value in a specific property, we can append <dot> Property name to the name of our Select Field.

JavaScript

the add button just simply adds a new object to the petsSelection array with properties petType and petFood initialized to empty string. Now at any row you make a selection, you are sure to add the values to this new object!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement