Search code examples
javascriptreactjsreduxreact-reduxredux-form

Redux-Form repeatable field


I am using Redux-Form v.5.2.3. I have a text input that needs to be repeated x number of times, depending on how many times a user clicks a button. Currently, because I am generating the same input field with the same field name, it does not work. When I type something on one input, it automatically types the same thing in the other inputs - that is because of the same name.

I am thinking of generating a unique id and appending that to the field 'name' - for example :

Original field:

Name: <input type="text" {...name}>

2nd Field - generated after the button press:

Name: <input type="text" {...name2}>

X field - generated after x button presses:

Name: <input type="text" {...nameX}>

Any ideas if that works and an example how to implement?

Thanks in advance


Solution

  • I would check out deep forms in the RF docs.

    Trying to figure this out as well, but from what I understand, you can define an array of fields by using the [] notation.

    export const fields = [
      'name[]',
    ];
    

    Then you add additional fields by using addField(value?, index?). You can then access each field by treating this.props.fields.name as the array of name fields.

    For your case, I think it should look something like

    <div>
      {this.props.fields.name.map((field, index) => (
        <input key={index} type="text" {...field} />
      )}
    </div>