useCollection
Provides functionality for managing and manipulating repeatable form fields within a form context.
Collection Props
name
Required
Name of the fields collection
connect
Allows you to connect your collection to a form.
defaultValue
Allows you to pass defaultValue to the collection, that will be apply if there is no initialValues. That defaultValue overrides collection fields default values.
Collection Values
keys
Array of autogenerated keys for each collection item.
length
Number of items in the collection.
insert(index, data)
Allows to add an item at specified index.
insertMultiple(index, data)
Allows to add a list of items at specified index.
append(data)
Allows to add an item at the end of the collection.
prepend(data)
Allows to add an item at the begin of the collection.
remove(index)
Allows to remove an item at specified index.
removeMultiple(indexes)
Allows to remove multiple items at specified indexes.
set(collection)
Allows to change the value of all the collection.
// Case with collection defined in a form context
const collection = useCollection({
name: "members",
});
{
collection.keys.map((key, index) => (
<div key={key}>
<MyField name={`members[${index}].name`} />
</div>
));
}
// Case with collection and form defined at same level
const form = useForm();
const collection = useCollection({
name: "members",
connect: form,
});
{
collection.keys.map((key, index) => (
<div key={key}>
<MyField name={`members[${index}].name`} />
</div>
));
}