Use FieldArray to deal with multiple similar fields

InstructorRory Smith

Share this video with your friends

Send Tweet

There can be situations in which the user needs to add or remove fields from a form depending on the amount of fields they need to fill out. Using redux-form, we can use the built-in FieldArray component to easily deal with this situation.

Justin Noel
~ 6 years ago

If the user taps the button to add a discount code, you can make the discount code required by adding validate={[required]} to the definition of the Field.

export const discounts = ({ fields }) => (
  <div className="custom-field-array-container">
    {fields.map((code, index) => (
      <div key={index} className="field-array-item">
        <Field
          name={code}
          type="text"
          component={customInput}
          label={`Discount Code #${index + 1}`}
          autoFocus
          validate={[required]}
        />
        <button type="button" onClick={() => fields.remove(index)}>
          &times;
        </button>
      </div>
    ))}
    <button type="button" onClick={() => fields.push()}>
      Add {!fields.length ? 'Discount Code(s)' : 'Another'}
    </button>
  </div>
);
Justin Noel
~ 6 years ago

How can you pre-populate or initialize the fields based on existing discount codes? For example, in RegisterForm.js, how can you pass down to the component some existing values?

I'm looking for something like this:

<FieldArray name="discountCodes" component={discounts} fields={ this.state.discountCodoes }/>
Rory Smithinstructor
~ 6 years ago

How can you pre-populate or initialize the fields based on existing discount codes?

Hi Justin, you can do this with this.props.initialize inside a redux-form component. Try adding this:

  componentWillMount() {
    this.props.initialize({ discountCodes: ['hello', 'world'] })
  }
Justin Noel
~ 6 years ago

Thanks Rory. That did the trick. Here's a working sample:

https://codesandbox.io/s/3x7p6pz0jq

I've got another question/concern about FieldArray's but I'll post it after I get a good working sample.

Justin Noel
~ 6 years ago

Okay Rory, here is my sample:

https://codesandbox.io/s/q3rxn5oj76 (See RegisterForm.js to see what I'm trying to do.

In my project, I can't have the "add more discount codes" button within the component that generates the fields. It has to be external to the FieldArray due to design layout issues.

So, how can I have an external button that triggers pushing onto the fields array?

Justin Noel
~ 6 years ago

Rory,

I finally found a solution for this via StackOverflow: https://stackoverflow.com/a/41607591/75644

When I get a chance, I'll update my sample above to include the fix for this.

Justin Noel
~ 6 years ago

Here's my solution to this problem:

https://calendee.com/2018/09/22/adding-to-redux-form-fieldarray/