Skip to main content

useFieldArray

Hook to easily manage a single field whose value is an array.

import { useFieldArray } from "@mozartspa/mobx-form"

Type#

function useFieldArray(
name: string,
options: UseFieldArrayOptions = {}
): UseFieldArrayResult

UseFieldArrayOptions#

Configuration to pass to useFieldArray()

form#

form?: Form<Values> | undefined

The form instance this field should be bound to. If not specified, it will be used the form instance available in FormContext.


UseFieldArrayResult#

It is returned by useFieldArray() and represents the field instance that gives access to props and methods to easily manage the field.

name#

name: string

The name of the field.


value#

value: T[]

The array value of the field.


names#

names: string[]

The array of field names (with dot notation) of the items contained in the array value of this field value. For example, if the form values are:

{
colors: ["red", "blue", "green"]
}

then using useFieldArray("colors") you would get:

const colorsField = useFieldArray("colors")
colorsField.names // ["colors.0", "colors.1", "colors.2"]

form#

form: Form

The Form instance this field is bound to.


setValue#

setValue: (value: T[]) => void

Sets the array value of the field.


push#

push: (...items: T[]) => void

Adds items at the end of the array value of the field.


pop#

pop: () => T | undefined

Pops the last item from the array value of the field.


unshift#

unshift: (...items: T[]) => void

Adds items at the beginning of the array value of the field.


insertAt#

insertAt: (index: number, item: T) => void

Inserts an item at specific index into the array value of the field.


removeAt#

removeAt: (index: number) => T | undefined

Removes an item at specific index from the array value of the field.


remove#

remove: (item: T) => void

Removes an item from the array value of the field.


clear#

clear: () => void

Sets the array value of the field to [].