Skip to main content

Field Array

The purpose of the FieldArray component is to make implementing repeating fields much simpler. There are some nuanced technical reasons as to why iterating over an array and rendering out Field components doesn't work, which the FieldArray component solves invisibly.

Examples

Simple

import React from 'react';

import { ReactForms, Form, FieldArray, Field } from '@rexlabs/form';
import { TextInput } from '@rexlabs/text-input';

const initialValues = {
friends: ['Luke', 'Obi-wan']
};

export function FieldArrayForm() {
return (
<ReactForms initialValues={initialValues}>
{() => {
return (
<Form>
<FieldArray name='friends'>
{({ fields, push }) => {
return (
<div>
{fields.map(({ field }, index) => {
return (
<div key={index}>
<Field
// `name` comes from the `field`
{...field}
label='Friend'
Input={TextInput}
/>
</div>
);
})}
<button
type='button'
onClick={() => {
// This will add a new field with a `value` of `''`
push('');
}}
>
Add friend
</button>
</div>
);
}}
</FieldArray>
</Form>
);
}}
</ReactForms>
);
}

Nested fields

import React from 'react';

import { ReactForms, Form, Field, FieldArray } from '@rexlabs/form';

const initialValues = {
friends: [
{
firstName: 'Obi-wan',
lastName: 'Kenobi',
address: 'Tatooine'
}
]
};

export function NestedFieldArrayForm() {
return (
<ReactForms initialValues={initialValues}>
{() => {
return (
<Form>
<FieldArray name='friends'>
{({ fields, push }) => {
return (
<div>
{fields.map(({ field }, index) => {
const { name } = field;
return (
<div key={index}>
<Field
name={`${name}.firstName`}
label='First Name'
Input={TextInput}
/>
<Field
name={`${name}.lastName`}
label='Last Name'
Input={TextInput}
/>
<Field
name={`${name}.address`}
label='Address'
Input={TextInput}
/>
</div>
);
})}
<button
type='button'
onClick={() => {
// This will add a new field with the value pre-filled
push({
firstName: 'Luke',
lastName: 'Skywalker',
address: 'Tatooine'
});
}}
>
Add friend
</button>
</div>
);
}}
</FieldArray>
</Form>
);
}}
</ReactForms>
);
}