@Calendee

Adding to Redux-form FieldArray

Imagine you're creating a form that needs multiple discount codes for a checkout process. In React/React Native, you might use a FieldArray from the redux-form library.

It could look something like this:

When you submit the form, redux-form will provide you a values object that contains the nested discount codes.

This all works great except for one thing. Notice that the button to add more discount codes is INSIDE the component that generates the discount code fields. Each time you click the button, it pushes more fields onto the passed in array. What if you want/need to have the "Add Another Discount Code" button OUTSIDE the fields. For example, your design my call for an "add more" button to be in the header or somewhere else in the form.

This is the problem I faced with my app. I did a lot of digging and finally found this Stack Overflow post that had a solution. The gist is the redux-form has action creators (arrayPush, arrayUnshift, arrayPop, etc) to do various things with the fields in a FieldArray. You just need to access these action creators from outside the FieldArray.

You do this by adding the action creators to your props (see mapDispatchToProps). When adding arrayPush, you MUST alias it as another name or the action creator will not be added to your props.

Now, you can tap the external button to add discount codes to your form.

P.S. This example also shows how to initialize your FieldArray with existing values.

Here's a working example: