Array Field
Array field is special in the way that instead of generating everything you want at once, it is storing a 'blueprint' of field
and waiting for user interaction.
None of the fields places under arrayFields
will be visible unless user will click add
button or initialValue
will pass correct structure to draw fields from 'blueprint'
type ArrayFieldStructure = {
type: 'array';
arrayFields: ArrayFieldSchema;
arrayFieldLabel?: (
arrayFieldIndex: number,
name: string,
hideRemoveButton: boolean,
removeAction: () => void
) => ReactNode;
internalFieldsWrapper?: JSX.IntrinsicElements['div'];
internalFieldsAndLabelWrapper?: JSX.IntrinsicElements['div'];
appendButton: (onClickAction: () => void, fieldsCount: number) => ReactNode;
removeButton?: (onClickAction: () => void, index: number) => ReactNode;
hideAppendButton?: boolean;
defaultAppendValue?: () => Record<string, string>;
conditionalRender?: {
conditionalFields: ConditionalType[];
conditionalRulesChainOption?: 'AND' | 'OR';
};
fieldWrapperProperties?: JSX.IntrinsicElements['div'];
fieldLabel?: (name: string) => ReactNode;
validations?: Validation;
ariaRequired?: boolean;
disabled?: boolean;
}
const selectOptions = () => [
{ label: 'Pizza', value: 'pizza' },
{ label: 'Burger', value: 'burger' },
{ label: 'Taco', value: 'taco' },
]
const schema: FormSchema = {
myArrayField: {
type: 'array',
arrayFields: {
name: {
type: 'text'
},
favFood: {
type: 'select',
placeholder: 'Select favourite food',
fieldWrapperProperties: { className: 'mb-2' },
optionsList: selectOptions
}
}
}
}
const initialValue = {
myArrayField: [{
name: 'My name',
favFood: 'pizza'
},
{
name: 'My second Name',
favFood: 'burger'
}
]
}
We need to remember that name
and favFood
fields are the part of array field blueprint and we have to treat it inside the structure as normal array with indexes. We need to replicate the whole structure in initialValue
and the same structure will be generated during submit
action.
Let's' move to the example with and without initial values
Example without initial values
Example with initial values
Example with remove button
Example with add button inside each label
Example of Read only and blocked elements in field
It is very hard to describe how array fields are working under the hood, but since we already touched the blueprint
idea it is good to show examples of how to convert array field
to read only or to disabled field.
There are two ways of doing it.
Whole blueprint is 'blocked'
It is as easy as making field types inside array 'readOnly' or set the field to be disabled
Important User will always add new array element which will be disabled or 'readOnly'
Block only specific field in specific array index
It is crucial to understand that array field initially doesn't exist if there is no value passed inside initialValue
property, therefor when we are talking about blocking specific field in specific array index, we need to do this from initialValue
perspective.